我正在编写一个简单的查询,使用符合Tags
的对象,如果以下情况属实,则必须返回文档:
:image
:
开头,但不是图片:
所以我想要{ Tags : [":image", ":ianything", "somethingelse"] }
我写下以下内容:
db.myCollection.find({
Tags: {
$elemMatch: {
$eq: ":image"
},
$elemMatch: {
$ne: ":image",
$regex: /^:\w+$/
},
$elemMatch: {
$regex: /^\w+$/
},
$size: 3
}
}).limit(50)
但它没有按预期工作并返回{ Tags : [":image", "something", "somethingelse"] }
我错在哪里?
答案 0 :(得分:1)
您需要使用$and来组合条件:
db.myCollection.find({ $and: [
{ Tags: {
$elemMatch: {
$eq: ":image"
} } },
{ Tags: {
$elemMatch: {
$ne: ":image",
$regex: /^:\w+$/
} } },
{ Tags: {
$elemMatch: {
$regex: /^\w+$/
} } },
{ Tags: { $size: 3 } }
] });