EDIT: This is my Schema:
{
"_id": "salfjasdlkfjaslkdfj",
"data": [
{
"title": "data1",
"_id": "xxx",
//more fields
},
{
"title": "data2",
"_id": "yyy",
//more fields
},
{
"title": "data3",
"_id": "zzz",
//more fields
}
],
//more fields
}
and my query in mongoose looks like this:
mySchema.findOne(
id,
{"data": {$elemMatch: {"_id": {$in: ["xxxxx", "yyyyy"]}}}},
{},
function(err, data){
if(err){
console.log(err);
res.send(err);
return;
}
res.json(data);
}
);
I want to project 2 or more elements from the "data" array. However, with this code, the result always contains only one element from "data" even if the array after "$in" has 2 or more elements.
This works perfectly fine without the "$in" (that is, for projecting only one element from the "data" array).
according to https://jira.mongodb.org/browse/SERVER-3544, $elemMatch and $in should work with each other.
- Is there something wrong with my code?
- If $elemMatch and $in STILL don't work with each other, is there another way to project this?
EDIT: The expected output is this:
{
"_id": "salfjasdlkfjaslkdfj",
"data": [
{
"title": "data1",
"_id": "xxx",
//more fields
},
{
"title": "data2",
"_id": "yyy",
//more fields
},
]
}
I just tried this query but it gives me an empty array! "[ ]". I think I'm messing up the syntax somewhere, or something. I'm not sure.
mySchema.aggregate(
[
{$match: {"_id": id}},
{$unwind: "$data"},
{$match: {"data._id": {$in: ["xxx", "yyy"]}}},
{$project: {"data":1}}
],
function(err, data){
if(err){
console.log(err);
res.send(err);
return;
}
res.json(data);
}
);