Mongodb,嵌套数组中的search对象

我在MongoDB上有这些types的项目:

{ "_id": { "$oid" : "2" }, "waypoints": [ { "step": 0, "coordinates": [1,2] }, { "step": 1, "coordinates": [1,3] }, { "step": 2, "coordinates": [1,4] } ] } 

我试图在集合中find[1,2]来检索waypoints.step和_id,但结果不是我所期望的。

我想得到:

 { "_id": { "$oid" : "2" }, "waypoints": [ { "step": 0 } ] } 

但我得到:

 { "_id": { "$oid" : "2" }, "waypoints": [ { "step": 0, }, { "step": 1, }, { "step": 2, } ] } 

什么是正确的查询来实现我想要的?

我只知道坐标,我需要检索对象的_id和对应于我正在查找的坐标的步骤。

谢谢

你可以通过投影数据来做到这一点。 查询应该是:

 db.collection.find({"_id": { "$oid" : "2" }},{waypoints : {$elemMatch : {coordinates:[1,2]}}}) 

有关更多信息,请检查$ elemMatch运算符。

因为您正在通过coordinatessearch,所以可以这样做:

 db.test.find({'waypoints.coordinates': [1,2]}, {'waypoints.$': 1}) 

在投影中, $表示find坐标的waypoints组的索引。

你会得到的coordinates值与step ,但这是你可以做的最好的:

 { "_id": "2", "waypoints": [ { "step": 0, "coordinates": [ 1, 2 ] } ] }