如何匹配数组中的元素?MongoDB聚合



我需要检查数组中包含特定字段的所有文档。

例如,我有阵列

arr = ['a', 'b', 'a']

我想匹配字段my_letter等于a or b的所有文档。

我有文件:

[
{
_id: ObjectID(),
my_letter:'d'
},
{
_id: ObjectID(),
my_letter:'a'
},
{
_id: ObjectID(),
my_letter:'b'
}
]

我希望聚合返回

[
{
_id: ObjectID(),
my_letter:'a'
},
{
_id: ObjectID(),
my_letter:'b'
}
]

我在我的$match管道中尝试过这个

{
$match: {
_id: {
$elemMatch: {
$or: [
{ $eq: ["a"] },
{ $eq: ["b"] },
],
},
},
},
},

当然它不起作用。你建议如何完成$match管道?

db.collection.find({
my_letter: {
$in: [ "a", "b" ]
}
})

mongoplayground

db.collection.aggregate([
{
$match: {
my_letter: {
$in: [ "a", "b" ]
}
}
}
])

mongoplayground

最新更新