我试图对MongoDB 3.4进行查询,在其中为数组的一个特定元素添加一个字段。对象的示例:
{
"_id": 1,
"people": [
{
"name": "Jhon Smith",
"age": "30",
"state": "NY"
},{
"name": "Clint Mercer",
"age": "50",
"state": "NY"
},{
"name": "Walter Smith",
"age": "40",
"state": "WI"
}
]
}我想要做一个查询,在这个文档中添加一个属性,其中第一个人的名字中有"Smith“。示例:
{
"_id": 1,
"people": [
{
"name": "Jhon Smith",
"age": "30",
"state": "NY"
},{
"name": "Clint Mercer",
"age": "50",
"state": "NY"
},{
"name": "Walter Smith",
"age": "40",
"state": "WI"
}
],
"firstSmith": {
"name": "Jhon Smith",
"age": "30",
"state": "NY"
}
}我已经有了我想要的文档的_id,但是我不知道如何进行这样的查询。我试图在id和"$addFields“之后使用聚合和”$addFields“,但是我无法对这个字段进行查询,以找到我想要的内容。我认为这类似于"findOne“查询,但是我找不到任何在"$addFields”上工作的东西。
我不想让"firstSmith“成为一个数组,里面只有一个”人“,我想要它,就像在这个例子中一样。
我很感谢你能帮我这个忙。
发布于 2022-01-11 16:19:33
$match -过滤相关文档$filter with $regexMatch -通过name属性筛选people数组arrayElemAt -只获取上面数组的第一个元素$addFields -从上述结果中添加具有值的新字段db.collection.aggregate([
{
"$match": {
"_id": 1
}
},
{
"$addFields": {
"firstSmith": {
"$arrayElemAt": [
{
"$filter": {
"input": "$people",
"cond": {
"$regexMatch": {
"input": "$$this.name",
"regex": "Smith"
}
}
}
},
0
]
}
}
}
])https://stackoverflow.com/questions/70669968
复制相似问题