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

标签 mongodb pymongo

我将使用 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/

相关文章:

python - python中的mongo查询

javascript - 如何使用客户端 JavaScript 在没有框架的情况下从 MongoDB 和 Node.js 服务器查找并返回数据?

mongodb - 带有 golang mongo-driver 的多个 maxPoolSize 配置

mongodb - 使用 Go 在 MongoDB 中指定查询

ruby-on-rails-3 - Mongo 查找器和标准

python - Pymongo 游标限制(1)返回超过 1 个结果

java - 如何使用 Java 在 mongodb 中上传 json 文件?

python - 显示存储在 MongoDB 中的 PNG 二进制图像

python - PyMongo 游标操作非常慢

python - 从 python 并行写入 MongoDb 集合