问题描述
我的数据库示例:
如果它是 Comedy
或 Romance
,我想投影流派数组的第一个元素。
我试过这个:
db.shows.find(
{},{ genres: { $elemmatch: { $or: [{ $eq: 'Drama' },{$eq: 'Comedy'}] } } }
);
但它给了我这个错误“未知的顶级运算符:$eq”。
解决方法
使用$in
$in 运算符选择字段值等于指定数组中任何值的文档。要指定 $in 表达式,请使用以下原型:
演示 - https://mongoplayground.net/p/MAuWUeP9GIE
db.collection.find({
genres: {
$elemMatch: {
"$in": [ "Drama","Comedy" ]
}
}
})
演示 - https://mongoplayground.net/p/JJJkoHuz_DZ
db.collection.find({},{
genres: {
$elemMatch: {
"$in": [ "Drama","Comedy" ]
}
}
})