node.js - Mongodb,在嵌套数组中搜索对象

标签 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 以及与我要查找的坐标相对应的步骤。

谢谢

最佳答案

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

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

欲了解更多信息,请查看$elemMatch运算符。

关于node.js - Mongodb,在嵌套数组中搜索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21047314/

相关文章:

java - 复合索引是否支持索引字段前缀的匹配?

javascript - 将磁盘空间存储在文件中

javascript - 当 Node.js 调用 HTML 时,外部 Javascript 和 CSS 不会影响 HTML

node.js - 在需要时初始化模块

javascript - Magento 使用 Node JS/soap 包过滤 SOAP v2

node.js - MongoDB 是否有使用类似 Mongoose 语法的(GUI)工具?

node.js - 图片下载后的回调函数

javascript - Parcel 错误 - 找不到模块 @parcel\fs-search\fs-search.win32-x64-msvc.node

javascript - Meteor.js 集合未在 mongo 中创建

node.js - 这是结合 MongoDB 和 Redis 的好方案吗?