Make $elemMatch (projection) return all objects that match criteria

前端 未结 3 1230
死守一世寂寞
死守一世寂寞 2020-12-24 07:09

I will use the example from here

{
 _id: 1,
 zipcode: 63109,
 students: [
              { name: \"john\", school: 102, age: 10 },
              { name: \"je         


        
3条回答
  •  情歌与酒
    2020-12-24 08:12

    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
    }
    

提交回复
热议问题