Sanka
Sanka

Reputation: 1324

MongoDB Query Dynamic keys

Need to find quoteIds where having different values and keys should start with 1 or 2 or 3. Could you please help.

{
 "quoteId": 1,
 "screening": {
    "101": 1,
    "201": 1,
    "301": 1,
    "100": 1,
    "200": 1,
    "300": 1,
    "111": 1,
    "211": 1,
    "311": 1
  }
}

{
 "quoteId": 2,
 "screening": {
    "101": 1,
    "201": 1,
    "301": 1,
    "100": 1,
    "200": 1,
    "300": 1,
    "111": 1,
    "211": 2,
    "311": 1
  }
}

Upvotes: 0

Views: 738

Answers (1)

Yong Shun
Yong Shun

Reputation: 51195

  1. $set - Create screenings array field, by converting object (key-value pair) to multiple documents (via $objectToArray) and fulfill the regex with starting of 1 or 2 or 3 in $filter.

  2. $match - Filter documents that screenings is not an empty array.

  3. $unset - Remove screenings field.

db.collection.aggregate([
  {
    $set: {
      screenings: {
        $filter: {
          input: {
            "$objectToArray": "$screening"
          },
          cond: {
            "$regexMatch": {
              input: "$$this.k",
              regex: "^(1|2|3)"
            }
          }
        }
      }
    }
  },
  {
    $match: {
      screenings: {
        $ne: []
      }
    }
  },
  {
    $unset: "screenings"
  }
])

Sample Mongo Playground

Upvotes: 2

Related Questions