Reputation: 1142
I have documents with this structure:
{
"_id": 5863635009,
"players": [{
"hero_id": 10,
"slot": 132
}, {
"hero_id": 16,
"slot": 131
}, {
"hero_id": 1,
"slot": 130
}, {
"hero_id": 7,
"slot": 129
}, {
"hero_id": 75,
"slot": 128
}, {
"hero_id": 21,
"slot": 4
}, {
"hero_id": 123,
"slot": 3
}, {
"hero_id": 114,
"slot": 2
}, {
"hero_id": 68,
"slot": 1
}, {
"hero_id": 84,
"slot": 0
}]
}
I have to find all documents where 2 particular heroes present AND one of them should have slot <= 127 AND another one should have slot >= 128 (can't have slot <= 127 or >= 128 both at the same time)
For example I search for hero_id 10 and 114. hero_id=10 should have slot <= 127 while hero_id=114 slot >=128 OR hero_id=10 should have slot >= 128 while hero_id=114 slot <= 127
As I'm new to Mongo I'm not sure how to go further than this and then check manually results for the slots condition:
{players : {$elemMatch: {hero_id : 10, hero_id : 114} }}
Is it possible to do inside the query?
Upvotes: 0
Views: 397
Reputation: 37028
The literal translation to mongo query laguage:
db.collection.find({
$or: [
{
"$and": [
{
"players": {
"$elemMatch": {
"hero_id": 10,
"slot": { "$lte": 127 }
}
}
},
{
"players": {
"$elemMatch": {
"hero_id": 114,
"slot": { "$gte": 128 }
}
}
}
]
},
{ the alternative "or" condition goes here. It is very similar}
]
})
Upvotes: 1