我想找到所有缺少数组中至少一个值的文档。例如:
数组:["spanish", "dutch", "french"]
应选择以下文档 :
{
translations: [{ language: "spanish" }]
}
//and
{
translations: [{ language: "spanish" }, { language: "french" }]
}
//and
{
translations: [{ language: "german" }]
}
但是应该不选择这些内容:
{
translations: [{ language: "spanish" }, { language: "french" }, { language: "dutch" }]
}
//and
{
translations: [{ language: "spanish" }, { language: "french" }, { language: "dutch" }, { language: "german" }]
}
答案 0 :(得分:3)
您可以使用$setIntersection
查找与$size
相交小于三个的文档
{$expr :
{$lt :[
{$size :{$setIntersection : ["$translations.language", ["spanish", "dutch", "french"]]}},
3
]}
}
收藏
> db.t80.find()
{ "_id" : ObjectId("5c68552ac6f8be1a888e6cc7"), "translations" : [ { "language" : "spanish" } ] }
{ "_id" : ObjectId("5c68552ac6f8be1a888e6cc8"), "translations" : [ { "language" : "spanish" }, { "language" : "french" } ] }
{ "_id" : ObjectId("5c68552ac6f8be1a888e6cc9"), "translations" : [ { "language" : "german" } ] }
{ "_id" : ObjectId("5c68552ac6f8be1a888e6cca"), "translations" : [ { "language" : "spanish" }, { "language" : "french" }, { "language" : "dutch" } ] }
{ "_id" : ObjectId("5c68552ac6f8be1a888e6ccb"), "translations" : [ { "language" : "spanish" }, { "language" : "french" }, { "language" : "dutch" }, { "language" : "german" } ] }
>
结果
> db.t80.find({$expr : {$lt :[{$size :{$setIntersection : ["$translations.language", ["spanish", "dutch", "french"]]}},3]}})
{ "_id" : ObjectId("5c68552ac6f8be1a888e6cc7"), "translations" : [ { "language" : "spanish" } ] }
{ "_id" : ObjectId("5c68552ac6f8be1a888e6cc8"), "translations" : [ { "language" : "spanish" }, { "language" : "french" } ] }
{ "_id" : ObjectId("5c68552ac6f8be1a888e6cc9"), "translations" : [ { "language" : "german" } ] }
>
答案 1 :(得分:2)
$all
返回包含某个键的所有项,这些键具有目标数组中的所有项$not
则相反。由于至少一个缺少的=不包含全部 查询如下:
{ "translations.language": { $not: { $all: ["spanish", "dutch", "french"] } } }
对于Mongoose
和Node.js
,它看起来像这样:
const target = ["spanish", "dutch", "french"];
Lang.find({ "translations.language": { $not: { $all: target } } })
.then(console.log)
.catch(console.error);
答案 2 :(得分:1)
替代解决方案:
db.docs.find({$or: [
{translations: {$not: {$elemMatch: {language: "spanish"}}}},
{translations: {$not: {$elemMatch: {language: "dutch"}}}},
{translations: {$not: {$elemMatch: {language: "french"}}}},
]})