Reputation: 349
I am trying to do a query that searches a value into many sub arrays using MongoDB. The db schema looks like this :
user:
[
{
name: "SomeName",
dvd: [
{
collectionName: "ActionDVDs",
movies: [
{
_id: ObjectId(X),
mark: 10
},
{
_id: ObjectId(Y),
mark: 8
}
}
]
}
...
]
I know three informations : user.name, dvd.collectioName, movies._id.
For example i am trying to know if there is any user named "SomeName", having a movie with the ObjectId(X) into the dvd collection named "ActionDVDs".
I already tried this query :
user.findOne(
{
$and: [
{name: "SomeName"},
{dvd : {
$elemeMatch: { name: "ActionDVDs" }
},
{movies: {
$elemMatch: { _id: ObjectId(X) }
}
]
})
Any idea ?
Upvotes: 3
Views: 1637
Reputation: 180937
This should do it, you need to nest the check for movies
inside dvd
, or it'll match the movie inside any movie collection;
db.user.findOne(
{'name':'SomeName',
'dvd': {$elemMatch: {'collectionName':'ActionDVDs',
'movies': {$elemMatch: { '_id': ObjectId('X')}}}}})
Upvotes: 4
Reputation: 4847
I think this will give you a clue:
user.find({
name: "SomeName",
"dvd.name": "ActionDVDs",
"dvd.movies._id": ObjectId(X)
})
Upvotes: 4