简体   繁体   English

mongodb - 按字段名的值查询文档

[英]mongodb - query documents by value of field name

Given I have these documents in User collection: 鉴于我在User集合中有这些文档:

{
  userId: "user-a",
  points: {
    date: {
      1: 100,
      5: 20,
      11: 65,
    },
  },
}

{
  userId: "user-b",
  points: {
    date: {
      31: 20,
      25: 40,
      11: 15,
    },
  },
}

What I want to do is I want to query users with points.date.[number] value exist and [number] < 7 for example. 我想要做的是我想用points.date.[number]查询用户points.date.[number]值存在, [number] <7例如。 How can I do that ? 我怎样才能做到这一点 ?

Since your keys are unknown you have to convert them to some key value pair using $objectToArray aggregation and then can easily $match with it 由于您的密钥未知,您必须使用$objectToArray聚合将它们转换为某个键值对,然后可以轻松地与它$match

db.collection.aggregate([
  { "$match": { "points.date[number]": { "$exists": true }}},
  { "$addFields": {
    "match": {
      "$objectToArray": "$points.date"
    }
  }},
  { "$match": { "match.k": { "$lt": "7" }}},
  { "$project": { "match": 0 }}
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MongoDB脚本通过查询更新所选文档中的字段 - MongoDB Script to update field in select documents with query MongoDB 查询具有 integer 值的字段 - MongoDB query on a field with integer value 如何获取集合 MongoDB 中多个文档的单个字段值? - How to fetch the single field value of multiple documents in a collection MongoDB? MongoDB:递减所有字段值高于定义的文档 - MongoDB: Decrement all documents with field value higher then defined 在回送中查询mongodb文档 - Query mongodb documents in loopback 基于匹配的查询MongoDB NodeJS更新所有文档和嵌入文档中的字段 - Update a field in all documents and embedded documents based on matching query MongoDB NodeJS 如何在一次查询中对mongodb中的多个字段和多个文档进行递增 - How to increment value in multiple fields and multiple documents in mongodb in one query 查询特定数组字段中是否存在值 - 集合中的所有文档 - Query for existence of a value in a specific array field - All documents within a collection 查询依赖于mongodb中其他文档的值的文档 - query documents that depend on values of other documents in mongodb 将一个新字段添加到集合的所有文档中,将文档字段中的值添加到 MongoDB (Mongoose) 中,记录为 300K+ - Add a new field to all documents of a collection with the value from the document field into MongoDB (Mongoose) with records of 300K+
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM