gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:13:27 25 4
gpt4 key购买 nike

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

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

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

最佳答案

如果你只需要匹配单个条件,那么点符号就足够了。在 Mongo 外壳中:

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

关于mongoDB查询以在嵌套数组中查找文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39338112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com