$elemMatch (projection) returns only one array element
See original GitHub issueLet’s say we have the following schemas:
var commentSchema = new Schema({
content: [String]
});
var postSchema = new Schema({
comments: [{type: Schema.ObjectId, ref: 'Comment'}]
});
When I need to find a post with some comments restricted by id I do the following query:
var ids = ['50478c35889a450000000001', '50478c35889a450000000002'];
Post.findById(req.param('post_id'))
.select({ comments: { $elemMatch: {$in: ids }}})
.exec(function (err, doc) {
console.log(doc.comments); // ['50478c35889a450000000001'] <- returns only one comment id
done(err);
});
Why I’m getting only the one comment id?
Issue Analytics
- State:
- Created 11 years ago
- Reactions:1
- Comments:14
Top Results From Across the Web
$elemMatch (projection) — MongoDB Manual
The $elemMatch operator limits the contents of an <array> field from the query results to contain only the first element matching the $elemMatch...
Read more >Make $elemMatch (projection) return all objects that match ...
In order to return multiple subdocuments, you're going to need to use the aggregation framework. This will return all of the subdocuments you're...
Read more >MongoDB Projection operator - $elemMatch - w3resource
The $elemMatch projection returns only the first matching element (although it matches more than one elements) of the tran_details array where ...
Read more >MongoDB return only matching array elements
In this topic, you will learn to return only matching array elements that satisfy the conditions. You can use the $elemMatch projection to ......
Read more >$elemMatch (projection) - MongoDB手册
However, the $elemMatch projection returns only the first matching element from the array. The document with _id equal to 3 does not contain...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
http://docs.mongodb.org/manual/reference/projection/elemMatch/
“Use the $elemMatch projection operator to limit the response of a query to a single matching element of an array.”
select() filters the fields returned by the query (findById). You should use where()