db.inventory.insertMany( [
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
{ item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
{ item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
{ item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
官网推荐使用{{}}和(.)的方式去逐层条件筛选。当时两者不太一样。
方法一:嵌套{{},{}}
db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )
这种查询需要保持嵌套格式一致甚至字段顺序一致,如果没有保持顺序一致也会无法得到匹配数据:
我们可以使用$eleMatch消除顺序一致性规则:
和想要的有点不一样,他是把array每个{}都打开,这样就会有两条数据返回。
The following example queries for documents where the instock
array has at least one embedded document that contains the field qty
equal to 5
and at least one embedded document (but not necessarily the same embedded document) that contains the field warehouse
equal to A。
这样就有两条数据返回。
aggregate方法查询
大多数人都以为是才智成就了科学家,他们错了,是品格。---爱因斯坦