mongoDB 查询以在嵌套数组中查找文档

Kri*_*lay 6 mongodb mongodb-query

[{
  "username":"user1",
  "products":[
           {"productID":1,"itemCode":"CODE1"},
           {"productID":2,"itemCode":"CODE1"},
           {"productID":3,"itemCode":"CODE2"},
       ]
},
{
  "username":"user2",
  "products":[
           {"productID":1,"itemCode":"CODE1"},
           {"productID":2,"itemCode":"CODE2"},
       ]
}]
Run Code Online (Sandbox Code Playgroud)

我想找到“user1”的“products”的所有“productID”,使得产品的“itemCode”是“CODE1”。

应该在 mongoDB 中编写什么查询来做到这一点?

Reu*_* L. 6

如果您只需要匹配单个条件,那么点表示法就足够了。在 Mongo 外壳中:

db.col.find({"products.itemCode" : "CODE1", "username" : "user1"})
Run Code Online (Sandbox Code Playgroud)

这将返回所有具有 itemCode“CODE1”的嵌套产品对象的用户。

更新

一开始不清楚你的要求,但应该是这样。

如果您希望每个产品作为单独的条目,则需要使用聚合框架。首先使用 拆分数组中的条目$unwind,然后$match根据您的条件使用。

db.col.aggregate(
  { $unwind: "$products" },
  { $match: { username: "user1", "products.itemCode": "CODE1" } }
);
Run Code Online (Sandbox Code Playgroud)

回复:

{ "_id" : ObjectId("57cdf9c0f7f7ecd0f7ef81b6"), "username" : "user1", "products" : { "productID" : 1, "itemCode" : "CODE1" } }
{ "_id" : ObjectId("57cdf9c0f7f7ecd0f7ef81b6"), "username" : "user1", "products" : { "productID" : 2, "itemCode" : "CODE1" } }
Run Code Online (Sandbox Code Playgroud)