I have a collection named Container with array of embedded documents called embeddedMany. Each embedded document is referencing several other documents named Referenced and these references are stored in array called referenceMany. The document looks like this.
{
"_id" : ObjectId("5a312337ea5cb32d30005d25"),
"embeddedMany" : [
{
"referencedMany" : [
DBRef("Referenced", ObjectId("5a312337ea5cb32d30005d24"), "myDb"),
DBRef("Referenced", ObjectId("5a312337ea5cb32d30005d23"), "myDb")
]
},
{
"referencedMany" : [
DBRef("Referenced", ObjectId("5a312337ea5cb32d30005d23"), "myDb")
DBRef("Referenced", ObjectId("5a312337ea5cb32d30005d22"), "myDb")
]
},
{
"referencedMany" : [
DBRef("Referenced", ObjectId("5a312337ea5cb32d30005d24"), "myDb")
DBRef("Referenced", ObjectId("5a312337ea5cb32d30005d22"), "myDb")
]
}
],
}
Now I need to find all embedded documents that reference certain document. Let's say this one: DBRef("Referenced", ObjectId("5a312337ea5cb32d30005d22"), "myDb")
.
I need the resulting document to look like this:
{
"_id" : ObjectId("5a312337ea5cb32d30005d25"),
"embeddedMany" : [
{
"referencedMany" : [
DBRef("Referenced", ObjectId("5a312337ea5cb32d30005d23"), "myDb")
DBRef("Referenced", ObjectId("5a312337ea5cb32d30005d22"), "myDb")
]
},
{
"referencedMany" : [
DBRef("Referenced", ObjectId("5a312337ea5cb32d30005d24"), "myDb")
DBRef("Referenced", ObjectId("5a312337ea5cb32d30005d22"), "myDb")
]
}
],
}
I read this very similar problem. So I guess I need to use aggregation and filter the embeddedMany field. My aggregation looks like this so far:
db.Container.aggregate(
[
{
$match: {
"embeddedMany.referencedMany.$id": ObjectId("5a312337ea5cb32d30005d22")
}
},
{
$project: {
"embeddedMany": {
"$filter": {
"input": "$embeddedMany",
"as": "embedded",
"cond": {
"$eq": [
"$$embedded.referencedMany.$id",
ObjectId("5a312337ea5cb32d30005d22")
]
}
}
}
}
},
]
);
And this is where I hit the wall. Because the MongoDB has the outstanding bug that prevents me from comparing $id
in the $eq
expression. There are some mentions about using $objectToArray
as hack but I couldn't pull it off all together.
Any help would be highly appreciated.