使$ elemMatch(投影)返回所有符合条件的对象 [英] Make $elemMatch (projection) return all objects that match criteria

查看:76
本文介绍了使$ elemMatch(投影)返回所有符合条件的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将使用此处

{
 _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 },
           ]
}


如果我运行


If I run

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

它将给出每个数组的第一结果.命名:

It will give the first result of each array. Naming this:

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


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


How can I make it return all the object of the array (and not only the first) that match the criteria? Meaning this:

{
 _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 }]}

推荐答案

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

In order to return multiple subdocuments, you're going to need to use the aggregation framework. This will return all of the subdocuments you're looking for:

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

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

You can do various things to get different output, but this will return:

{
    "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
}

这篇关于使$ elemMatch(投影)返回所有符合条件的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆