gpt4 book ai didi

mongodb - 使 $elemMatch (projection) 返回所有符合条件的对象

转载 作者:IT老高 更新时间:2023-10-28 13:06:21 24 4
gpt4 key购买 nike

我将使用 here 中的示例

{
_id: 1,
zipcode: 63109,
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
]
}
{
_id: 2,
zipcode: 63110,
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}

{
_id: 3,
zipcode: 63109,
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
]
}

{
_id: 4,
zipcode: 63109,
students: [
{ name: "barney", school: 102, age: 7 },
]
}

如果我跑了

db.schools.find( { zipcode: 63109 },
{ students: { $elemMatch: { school: 102 } } } )

它将给出每个数组的first结果。命名:

{ "_id" : 1, "students" : [ { "name" : "john", "school" : 102, "age" : 10 } ] }
{ "_id" : 3 }
{ "_id" : 4, "students" : [ { "name" : "barney", "school" : 102, "age" : 7 } ] }

如何让它返回符合条件的数组的所有对象(而不仅仅是第一个对象)?意思是:

{
_id: 1,
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 }
]
}
{ _id: 3 }
{_id: 4, students: [ { name: "barney", school: 102, age: 7 }]}

最佳答案

为了返回多个子文档,您需要使用聚合框架。这将返回您要查找的所有子文档:

db.zip.aggregate(
{$match: {zipcode: 63109}},
{$unwind: "$students"},
{$match: {"students.school": 102}}
)

你可以做各种事情来获得不同的输出,但这会返回:

{
"result" : [
{
"_id" : 1,
"zipcode" : 63109,
"students" : {
"name" : "john",
"school" : 102,
"age" : 10
}
},
{
"_id" : 1,
"zipcode" : 63109,
"students" : {
"name" : "jess",
"school" : 102,
"age" : 11
}
},
{
"_id" : 4,
"zipcode" : 63109,
"students" : {
"name" : "barney",
"school" : 102,
"age" : 7
}
}
],
"ok" : 1
}

关于mongodb - 使 $elemMatch (projection) 返回所有符合条件的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19696282/

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