使用elemMatch对嵌套数组数据进行MongoDB查询并仅返回匹配元素

时间:2017-10-12 12:58:37

标签: arrays mongodb

{
"_id" : NumberLong(107),
"cnic" : NumberLong(098765),
"recordsOFGt" : [ 
    {
        "records" : [ 
            {
                "_id" : NumberLong(1),
                "contactIds" : [ 
                    NumberLong(303)
                ],
            },
            {
                "_id" : NumberLong(2),
                "contactIds" : [ 
                    NumberLong(303),
                    NumberLong(304)
                ],
            },
            {
                "_id" : NumberLong(3),
                "contactIds" : [ 
                    NumberLong(309),
                    NumberLong(304)
                ],
            },
            {
                "_id" : NumberLong(4),
                "contactIds" : [ 
                    NumberLong(303),
                    NumberLong(304)
                ],
            },
            {
                "_id" : NumberLong(5),
                "contactIds" : [ 
                    NumberLong(303),
                    NumberLong(304)
                ],
            },
        ]
    },
    "records2" : {
     ...
     ...
    }
]
}

我只想要通过_id匹配的记录元素我已尝试过这个

db.getCollection('tempCollection').findOne(    
  { 'recordsOFGt': {$elemMatch: {'records._id': 1} }},
  {'recordsOFGt.$': 1}
)

这将返回记录数组的所有元素,只需匹配元素。

这就是我想要的输出:

{

     "records" : 
          {
               "_id" : NumberLong(1),
               "contactIds" : [ 
                     NumberLong(303)
               ],
          }

}

0 个答案:

没有答案