简体   繁体   中英

mongodb - query documents by value of field name

Given I have these documents in User collection:

{
  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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM