Reputation: 557
i have a collection that contain documents with of the structure:
{
"userId": "57e32f05-fca1-452c-aace-76f35962fe4a",
"availableSearches": {
"7fcb6d67-f825-41ca-b47c-fecaedc738c7": {
"searchType": "RECENT",
"searchId": "7fcb6d67-f825-41ca-b47c-fecaedc738c7",
"enabled": false,
}
"2b59ee7b-256b-47c2-9573-18676951cb0d": {
"searchType": "RECENT",
"searchId": "2b59ee7b-256b-47c2-9573-18676951cb0d",
"enabled": true,
}
}
}
I have a list of ids:
["7fcb6d67-f825-41ca-b47c-fecaedc738c7",
"2b59ee7b-256b-47c2-9573-18676951cb0d",
...]
The keys of availableSearches
object are unknown.
I want to get all documents in 1 query, that availableSearches.${KEY}
exists or availableSearches.${KEY}.searchId
equals to ${KEY}
. I.e documents that matches the keys in the list.
Is there a way to do it in mongodb?
Upvotes: 1
Views: 374
Reputation: 17915
You can try below aggregation query :
db.collection.aggregate([
/** Add a new field to all docs where `availableSearches` will converted to an array of [{k:...,v:...},{k:...,v:...}]*/
{
$addFields: { availableSearchesConverted: { $objectToArray: "$availableSearches" } }
},
/** Match on k field of new array */
{
$match: {
"availableSearchesConverted.k": {
$all: [ // Use `$in` if you wanted to get docs if atleast one value exists. `$all` checks for all input elements should exists
"7fcb6d67-f825-41ca-b47c-fecaedc738c7", "2b59ee7b-256b-47c2-9573-18676951cb0d"
]
}
}
},
/** Remove newly created field from output */
{
$project: {
availableSearchesConverted: 0
}
}
])
Test : mongoplayground
Upvotes: 1