Mongodb,嵌套数组中的搜索对象

时间:2014-01-10 14:51:13

标签: node.js mongodb

我在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和与我正在寻找的坐标对应的步骤。

感谢

2 个答案:

答案 0 :(得分:1)

您可以通过投影数据来实现。查询应为:

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

有关详情,请查看$elemMatch运营商。

答案 1 :(得分:0)

因为您正在coordinates进行搜索,所以您可以这样做:

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

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

您将获得coordinates值以及step,但这是您可以做的最好的事情:

{
  "_id": "2",
  "waypoints": [
    {
      "step": 0,
      "coordinates": [
        1,
        2
      ]
    }
  ]
}
相关问题