MongoDB查询嵌套数组中的文档

7
[{
  "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"},
       ]
}]

我想找到所有"products"中"itemCode"为"CODE1"的"productID",并且这些产品是"用户1"所拥有的。

应该如何编写MongoDB查询语句呢?


请检查我的更新答案。 - Reuben L.
@ReubenL。谢谢。 - Krisalay
我会依次使用 $match -> $unwind -> $replaceRoot -> $match -> $project - aderchox
3个回答

7

如果您只需要匹配单个条件,则点符号表示法就足够了。 在Mongo shell中:

db.col.find({"products.itemCode" : "CODE1", "username" : "user1"})

这将返回所有具有itemCode为"CODE1"的嵌套产品对象的用户。
更新:
最初对您的要求不是很清楚,但这应该就是您想要的。
如果您希望每个产品作为单独的条目,则需要使用聚合框架。首先使用$unwind拆分数组中的条目,然后使用$match进行条件匹配。
db.col.aggregate(
  { $unwind: "$products" },
  { $match: { username: "user1", "products.itemCode": "CODE1" } }
);

响应:

{ "_id" : ObjectId("57cdf9c0f7f7ecd0f7ef81b6"), "username" : "user1", "products" : { "productID" : 1, "itemCode" : "CODE1" } }
{ "_id" : ObjectId("57cdf9c0f7f7ecd0f7ef81b6"), "username" : "user1", "products" : { "productID" : 2, "itemCode" : "CODE1" } }

这会给我用户2的产品,但我不想要。 - Krisalay
啊,我错过了那个要求,你可以将其作为附加参数添加。 - Reuben L.
db.col.find({"username": "user1", "products.itemCode" : "CODE1"}) - Reuben L.

1

你的问题的答案是

db.col.aggregate([
   { $unwind: "$products" },
   { $match: { username: "user1", "products.itemCode": CODE1 } },
   { $project: { _id: 0, "products.productID": 1 } }
]);

在我的情况下,如果没有 [ ] 标签就不起作用。

0

你需要多个过滤器,就像下面这样,这实际上是“AND”条件(假设你的集合名称为collection1

db.collection1.find({"username":"user1", "products.itemCode" : "CODE1"})

它不会起作用,因为最终它将返回整个数据,并将“username”设置为“user1”。 - Krisalay
在这种情况下,您应该使用$unwind。 - Reuben L.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接