gpt4 book ai didi

MongoDB:从数组中单独获取所有 $matched 元素

转载 作者:可可西里 更新时间:2023-11-01 10:08:59 28 4
gpt4 key购买 nike

我试图单独获取所有匹配的元素,here是示例数据和查询。

// json
[
{
"name": "Mr Cool",
"ican": [
{
"subcategory": [
{
"id": "5bffdba824488b182ec86f8d", "name": "Cricket"
},
{
"id": "5bffdba824488b182ec86f8c", "name": "Footbal"
}
],
"category": "5bffdba824488b182ec86f88",
"name": "Sports"
}
]
}
]

// query
db.collection.aggregate([
{
"$match": {
"ican.subcategory.name": { $in: ["Cricket","Football"] }
}
},
{
"$project": { "_id": 1, "name": 1, }
}
])

我得到的是综合结果,我需要个人比赛记录。我尝试了 $all$elementMatch 但得到了相同的响应。我怎样才能得到如下结果。我正在使用 $aggregate 因为我将使用 $geoNear 管道来获取附近的用户。

// current result
[
{
"_id": ObjectId("5a934e000102030405000000"),
"name": "Mr Cool"
}
]

// expected result
[
{
"_id": ObjectId("5a934e000102030405000000"),
"name": "Mr Cool",
"subcategory: "Cricket"
},
{
"_id": ObjectId("5a934e000102030405000000"),
"name": "Mr Cool",
"subcategory: "Footbal"
}
]

谢谢

最佳答案

试试这个 Mongo Playground

db.col.aggregate([
{"$unwind" : "$ican"},
{"$unwind" : "$ican.subcategory"},
{"$match" : {"ican.subcategory.name": { "$in": ["Cricket","Football"] }}},
{"$group" : {"_id" : null,"data" : {"$push" : {"_id" : "$_id","name" : "$name","subcategory" : "$ican.subcategory.name"}}}},
{"$unwind" : "$data"},
{"$replaceRoot" : {"newRoot" : "$data"}}
])

关于MongoDB:从数组中单独获取所有 $matched 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53540826/

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