Mongodb,在嵌套数组中搜索对象 [英] Mongodb, search object in nested Array

查看:58
本文介绍了Mongodb,在嵌套数组中搜索对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 mongodb 上有这些类型的项目:

I have these type of items on 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,但结果不是我所期望的.

I tried to find [1,2] in the collection to retrieve waypoints.step and the _id, but the result is not what i expected.

我想得到:

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

但我明白了:

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

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

what is the correct query to achieve what i want?

我只知道坐标,我需要检索对象的_id和我要找的坐标对应的步骤.

I know only the coordinates, i need to retrive _id of the object and the step corresponding to the coordinates I'm looking for.

谢谢

推荐答案

您可以通过投影数据来实现.查询应该是:

You can do it by projecting data. The query should be :

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

有关更多信息,请查看 $elemMatch 运算符.

For more information check $elemMatch operator.

这篇关于Mongodb,在嵌套数组中搜索对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆