gpt4 book ai didi

mongodb - 如何在MongoDB查询中过滤和映射文档数组?

转载 作者:行者123 更新时间:2023-12-03 13:43:27 24 4
gpt4 key购买 nike

因此,我的人员集合中包含以下文档:

{
"_id" : ObjectId("595c0630939a8ae59053a9c3"),
"name" : "John Smith",
"age" : 37,
"location" : "San Francisco, CA",
"hobbies" : [
{
"name" : "Cooking",
"type" : "Indoor",
"regular" : true
},
{
"name" : "Baseball",
"type" : "Outdoor",
"regular" : false
}
]
}
{
"_id" : ObjectId("595c06b7939a8ae59053a9c4"),
"name" : "Miranda Thompson",
"age" : 26,
"location" : "Modesto, CA",
"hobbies" : [
{
"name" : "Lego building",
"type" : "Indoor",
"regular" : false
},
{
"name" : "Yoga",
"type" : "Indoor",
"regular" : false
}
]
}
{
"_id" : ObjectId("595c078e939a8ae59053a9c5"),
"name" : "Shelly Simon",
"age" : 26,
"location" : "Salt Lake City, UT",
"hobbies" : [
{
"name" : "Hunting",
"type" : "Outdoor",
"regular" : false
},
{
"name" : "Soccer",
"type" : "Outdoor",
"regular" : true
}
]
}

我正在尝试仅对常规兴趣爱好过滤“兴趣爱好”数组,并投影字段_id,名称,年龄和兴趣爱好的名称和类型。

我希望我的输出是这样的:
{
"_id" : ObjectId("595c0630939a8ae59053a9c3"),
"name" : "John Smith",
"age" : 37,
"hobbies" : [
{
"name" : "Cooking",
"type" : "Indoor"
}
]
}
{
"_id" : ObjectId("595c06b7939a8ae59053a9c4"),
"name" : "Miranda Thompson",
"age" : 26,
"hobbies" : []
}
{
"_id" : ObjectId("595c078e939a8ae59053a9c5"),
"name" : "Shelly Simon",
"age" : 26,
"hobbies" : [
{
"name" : "Soccer",
"type" : "Outdoor"
}
]
}

好吧...我可以在mongo shell中使用以下命令实现此输出:
db.people.aggregate([
{
$project: {
hobbies: {
$filter: {
input: "$hobbies",
as: "hobby",
cond: { $eq: ["$$hobby.regular", true] }
}
},
name: 1,
age: 1
}
},
{
$project: {
"hobbies.name": 1,
"hobbies.type": 1,
name: 1,
age: 1
}
}
])

如您所见,我不得不依次使用两个$ project运算符,我觉得这很不好。

有没有一种方法可以用另一个查询来获得相同的结果,而另一个查询又不用两次按顺序使用相同的运算符?

最佳答案

您可以将$filter表达式包装在$map中以映射输出值。

db.people.aggregate([
{
"$project": {
"name": 1,
"age": 1,
"hobbies": {
"$map": {
"input": {
"$filter": {
"input": "$hobbies",
"as": "hobbyf",
"cond": "$$hobbyf.regular"
}
},
"as": "hobbym",
"in": {
"name": "$$hobbym.name",
"type": "$$hobbym.type"
}
}
}
}
}
])

关于mongodb - 如何在MongoDB查询中过滤和映射文档数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44914367/

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