I have this mongoose model:
var mySubEntitySchema = new Schema({
property1: String,
property2: String
});
var myEntitySchema = new Schema({
name: String,
sub: [mySubEntitySchema]
});
export var MyEntityModel: mongoose.Model<MyEntityDocument> = mongoose.model<MyEntityDocument>("MyEntity", myEntitySchema);
Now I want to get a specific MyEntityDocument for which I have the _id, but only with the subDocuments matching property1 = "example".
Is there any way to do that?
I tried a solution using Aggregate but without any success:
MyEntityModel.aggregate([
{$match: { "_id": myId, "sub.property1":"example" }},
{$unwind: "$sub"},
{$match: { "sub.property1":"example"}},
{$group: {"_id":"$_id","subs":{$push:"$sub"}}}
], (error, result) => {
console.log("Result = " + JSON.stringify(result));
}
});
But it returns nothing. If I don't put "_id": myId in the first $match clause, then I get results, but I only want the one result that corresponds to the _id I have.
Anyone knows how I can do this?
EDIT: As asked, here is an example.
With this data:
{
"_id": "54c12276fcb2488d300795e4",
"name": "a",
"sub": [
{
"_id": "54c12276fcb2488d300795e0",
"property1": "example",
"property2": "something"
},
{
"_id": "54c12276fcb2488d300795e1",
"property1": "notmuch",
"property2": "somethingelse"
},
{
"_id": "54c12276fcb2488d300795e2",
"property1": "notinteresting",
"property2": "something"
},
{
"_id": "54c12276fcb2488d300795e3",
"property1": "example",
"property2": "anotherthing"
}
]
},
{
"_id": "54c12277fcb2488d300795e5",
"name": "b",
"sub": [
{
"_id": "54c12276fcb2488d300795e6",
"property1": "example",
"property2": "word"
}
]
}
I want the entity with _id "54c12276fcb2488d300795e4" and the subdocs that match property1 = "example". So the expected result is:
{
"_id": "54c12276fcb2488d300795e4",
"name": "a",
"sub": [
{
"_id": "54c12276fcb2488d300795e0",
"property1": "example",
"property2": "something"
},
{
"_id": "54c12276fcb2488d300795e3",
"property1": "example",
"property2": "anotherthing"
}
]
}