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 } } )

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

这种查询需要保持嵌套格式一致甚至字段顺序一致,如果没有保持顺序一致也会无法得到匹配数据:

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

我们可以使用$eleMatch消除顺序一致性规则:

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

方法二:

结果:

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

 和想要的有点不一样,他是把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。

 这样就有两条数据返回。

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

 aggregate方法查询

相关文章:

  • 2021-12-03
  • 2021-09-19
  • 2022-12-23
  • 2022-01-22
  • 2022-02-16
  • 2022-12-23
  • 2022-03-06
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-09
  • 2022-12-23
  • 2021-03-31
  • 2021-06-12
  • 2021-09-04
相关资源
相似解决方案