mongodb的安装与使(三)之复杂操作 嵌套array查询,aggregate $unwind $match $project

mongodb多层嵌套查询

官网案例:

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方法查询

posted @ 2020-04-12 13:26  wqbin  阅读(861)  评论(0编辑  收藏  举报