我在mongodb上有以下类型的项目:

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


我试图在集合中找到[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运算符。

10-06 12:58
查看更多