Really stuck with something that to me seems like it should be easy
I want to essentially do is convert the string of an objectId to an objectId and match on that, but I can't figure out how to do it...!
To be clear, I can't use { x: ObjectId(someObjectId) } because I'm wanting to serialise the query to JSON
Data:
[{
"_id": {
"$oid": "5f37eaaae4102600180078a8"
},
"Details": "Something A",
"App": {
"$oid": "5f37cec069106932d4710ea6"
}
},{
"_id": {
"$oid": "5f3860f10a9db00018f2e2e3"
},
"Details": "Something B",
"App": {
"$oid": "5f37cec069106932d4710ea6"
}
},{
"_id": {
"$oid": "5f3908a7db8fd70018b19942"
},
"Details": "Something C",
"App": {
"$oid": "5f37cec069106932d4710ea7"
}
},{
"_id": {
"$oid": "5f390961db8fd70018b19945"
},
"Details": "Something D",
"App": {
"$oid": "5f37cec069106932d4710ea8"
}
}
]
And query with something like:
[
{
'$match': {
'App': {
'$eq': {
'$toObjectId': '5f37cec069106932d4710ea8'
}
}
}
}
]
the result obviously being:
{
"_id": {
"$oid": "5f390961db8fd70018b19945"
},
"Details": "Something D",
"App": {
"$oid": "5f37cec069106932d4710ea8"
}
}
CodePudding user response:
You can do it like this:
db.collection.aggregate([
{
"$match": {
"$expr": {
"$eq": [
"$App",
{
"$toObjectId": "5f37cec069106932d4710ea8"
}
]
}
}
}
])
