MongoDB $elemMatch with 2属性条件



我有这样的文档结构:

{
"_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
}]
}

我必须找到所有文档中出现的两个特定英雄,其中一个应该有插槽<= 127,另一个应该有插槽>= 128(不能同时有插槽<= 127或>= 128)

例如,我搜索hero_id 10和114。

hero_id=10应该有slot <= 127而hero_id=114应该有slot>=128或者hero_id=10应该有slot>=128而hero_id=114应该有slot <= 127由于我是Mongo的新手,我不确定如何走得更远,然后手动检查槽条件的结果:

{players : {$elemMatch: {hero_id : 10, hero_id : 114} }}

是否可以在查询中执行?

蒙古语查询语言的直译:

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}
]
})

最新更新