'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
}
}
Solution 1:[1]
$set- Createscreeningsarray 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.$match- Filter documents thatscreeningsis not an empty array.$unset- Removescreeningsfield.
db.collection.aggregate([
{
$set: {
screenings: {
$filter: {
input: {
"$objectToArray": "$screening"
},
cond: {
"$regexMatch": {
input: "$$this.k",
regex: "^(1|2|3)"
}
}
}
}
}
},
{
$match: {
screenings: {
$ne: []
}
}
},
{
$unset: "screenings"
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yong Shun |
