gpt4 book ai didi

mongodb - 如何只返回选定的几个嵌入对象的对象?

转载 作者:可可西里 更新时间:2023-11-01 09:54:52 26 4
gpt4 key购买 nike

我的结构如下:

{
day: x,
events:
[
{
year: y,
info: z
}
]
}

到目前为止,我创建了以下查询,我没有返回错误但也显示了任何内容(这是错误的)。

db.days.aggregate([
{
$match:
{
$and:
[
{
'day': 'March_13'
},
{
'events.year': '1870'
},
{
'events.info': {$regex: "./French./"}
}
]
}
},
{
$unwind: {path: "$events"},
},
{
$match:
{
'info': { $regex: '.*French.*'}
}
}])

根据我的阅读,我需要按 _id 分组,但我不知道如何用满足第二个 $match 的对象重新创建数组。

能否请您看看并告诉我为什么初始查询不起作用,并在组 block 上给我建议?

一些示例数据在这里:

{ 
"day" : "March_13",
"events" :
[
{
"year" : "1929",
"info" : "Peter Breck, American actor (d. 2012)"
},
{
"year" : "1929",
"info" : "Joseph Mascolo, American actor"
},
{
"year" : "1929",
"info" : "Zbigniew Messner, Polish economist and politician, 9th Prime Minister of the Republic of Poland (d. 2014)"
},
{
"year" : "1929",
"info" : "Bunny Yeager, American model and photographer (d. 2014)"
}
]
}

下面是我是否可以通过“American”这个词成功查询:

{ 
"day" : "March_13",
"events" :
[
{
"year" : "1929",
"info" : "Peter Breck, American actor (d. 2012)"
},
{
"year" : "1929",
"info" : "Joseph Mascolo, American actor"
},
{
"year" : "1929",
"info" : "Bunny Yeager, American model and photographer (d. 2014)"
}
]
}

基本上我想检查字段信息是否包含搜索到的词,如果包含我将其保存在数组中。

最佳答案

您想要尝试为上述示例运行以下聚合管道以获得所需的结果:

db.days.aggregate([
{
"$match": {
"day" : "March_13",
"events.year": "1929",
"events.info": /American/
}
},
{ "$unwind": "$events" },
{
"$match": {
"day" : "March_13",
"events.year": "1929",
"events.info": /American/
}
},
{
"$group": {
"_id": "$_id",
"day": { "$first": "$day" },
"events": { "$push": "$events" }
}
}

])

示例输出

/* 0 */
{
"result" : [
{
"_id" : ObjectId("5706b38dcc578484faab815f"),
"day" : "March_13",
"events" : [
{
"year" : "1929",
"info" : "Peter Breck, American actor (d. 2012)"
},
{
"year" : "1929",
"info" : "Joseph Mascolo, American actor"
},
{
"year" : "1929",
"info" : "Bunny Yeager, American model and photographer (d. 2014)"
}
]
}
],
"ok" : 1
}

关于mongodb - 如何只返回选定的几个嵌入对象的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36484796/

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