我想为mongoose中的嵌套对象查找一个基于键的文档.例如

{
     "_id": 1,
     "first_name": "Tom",
     "email": "tom@example.com",
     "ACL": {
        123gd: {
          read: true,
          write: false,
        },
        3sg2w: {
          read: true,
          write: false,
        }
     }
},
{
     "_id": 2,
     "first_name": "Tom",
     "email": "tom@example.com",
     "ACL": {
        546er: {
          read: true,
          write: false,
        },
        98trw: {
          read: true,
          write: false,
        }
     }
}

对于上面的示例文档数据,我想编写一个方法来查找并返回只有ACL key is 123gd个的文档.

{
     "_id": 1,
     "first_name": "Tom",
     "email": "tom@example.com",
     "ACL": {
        123gd: {
          read: true,
          write: false,
        },
        3sg2w: {
          read: true,
          write: false,
        }
     }
}

那么我怎样才能在mongoose中找到特定的文档呢

推荐答案

您可以通过$objectToArray实现这一点,将ACL对象转换为k-v元组array.然后可以使用$anyElementTrue判断k是否为123gd

db.collection.find({
  $expr: {
    "$anyElementTrue": {
      "$map": {
        "input": {
          "$objectToArray": "$ACL"
        },
        "as": "kv",
        "in": {
          $eq: [
            "$$kv.k",
            "123gd"
          ]
        }
      }
    }
  }
})

这是Mongo Playground英镑供你参考.

Mongodb相关问答推荐

如何将空值单独分组?

MongoDB与合并对象聚合

MongoDB - 将对象转换为数组

定期自动轮换 MongoDb 集合

在我的查询中使用 populate() 时的 MongoDB createIndex()

如何在 Mongo 聚合中合并文档中的数组字段

为什么 local.oplog.rs 上每隔几分钟的活动就会锁定 mongo 客户端

MongoDB插入引发重复键错误

字段类型在 MongoDB 索引中是否重要?

django 和 mongodb 是否使迁移成为过go ?

如何在mongoose中加入两个集合

MongoDB - 文件大小巨大且不断增长

REACT 获取发布请求

判断 mongoDB 是否连接

如何从 Mongoose 模型对象中获取集合名称

通过 Java 执行 Mongo like Query (JSON)

如何在mongoDB中检索其值以特定字符结尾的文档

如何在 Ubuntu 10.04 中使用 --auth 选项重新启动 mongodb?

为什么 Mongo 提示会使查询运行速度提高 10 倍?

如何在 Windows 上停止 mongodb 服务器?