如果一个值在文档数组中,我正在尝试匹配一条记录 或符合其他条件。我没有收到错误,但是没有返回记录。
任何帮助表示赞赏(我看过其他有关数组和聚合的文章-我也无法使它们正常工作-抱歉,这很可能是重复的内容
数据:
_id:5c93f908aa338366bd00b966
name:"Davidson"
type:["G"]
_id:5c93f908aa338366bd00b977
name:"Robertson"
type:["G","R"]
查询:
thing.aggregate([{
$match: {
$or: [
{
"name": {
$regex: "xx",
$options: "i"
}
},
{
"type": {
$elemMatch: {
"type": "G"
}
}
}
]
}
}])
答案 0 :(得分:2)
您不需要$elemMatch
:
db.col.aggregate([{
$match: {
$or: [
{
"name": {
$regex: "xx",
$options: "i"
}
},
{
"type": "G"
}
]
}
}])
它检查type
数组是否包含任何"G"