Using $elemMatch to filter a subdocument array generates error [Error: Can't use $elemMatch with ObjectId.]
See original GitHub issueHi, I want to get all the “activities” on the “sites” that are managed by a specific user so, I’ve tried to query activities with the following:
site: {
$elemMatch: {
managers: { // managers is an array of ObjectId
$in: [req.user._id] // this is an ObjectId
}
}
}
I’m getting the error [Error: Can’t use $elemMatch with ObjectId.] Can’t find much on that error on internet… Thanks!
Issue Analytics
- State:
- Created 8 years ago
- Comments:11
Top Results From Across the Web
Filtering an array, in a subdocument, in an ... - Stack Overflow
As such, this is the solution I'll go with; namely using #elemMatch to match those element(s) which contain embedded subdocuments and arrays ......
Read more >Is it possible to use $elemMatch within $filter? - MongoDB
Hi everyone, Is it possible to use elemMatch within filter? This is an example of my data: { "_id" : ObjectId("5e6c26153facb910290f0869"), ...
Read more >[Solved]-elemMatch search on array of subdocument-mongodb
It seems like you are trying to put work into the "projection" that you should be doing in the query. Rather your statement...
Read more >multiple filter in mongodb | The AI Search Engine You Control
MongoDB filter operator is used to filter the elements from the array field. We can use multiple condition like $gt, $lt, $gte and...
Read more >Functional Differences: Amazon DocumentDB and MongoDB
To use a sparse index that you have created in a query, you must use the $exists clause on the fields that cover...
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 Free
Top 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
If managers is an array of ObjectId, you should just use:
You could also use the below, but not recommended because
$elemMatch
is only necessary if you need to match arrays of subdocs by multiple criteria.The query you specified will assume that
site
is an array which contains subdocs with a “manager” key that’s an _id.one more on the queue of this issue