簡體   English   中英

MongoDB-查找至少缺少一個數組值的位置

[英]MongoDB - Find where at least one array value is missing

我想找到所有缺少數組中至少一個值的文檔。 例如:

數組: ["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" }]
}

您可以使用$setIntersection查找相交$size小於3的文檔

{$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" } ] }
>

使用$ all$ not運算符

  • $all返回包含某個鍵的所有項目,這些鍵具有目標數組中的所有項目
  • $not相反。 由於至少一個缺少的=不包含全部

查詢如下所示:

{ "translations.language": { $not: { $all: ["spanish", "dutch", "french"] } } }

使用MongooseNode.js ,它將如下所示:

const target = ["spanish", "dutch", "french"];

Lang.find({ "translations.language": { $not: { $all: target } } })
  .then(console.log)
  .catch(console.error);

替代解決方案:

db.docs.find({$or: [
 {translations: {$not: {$elemMatch: {language: "spanish"}}}},
 {translations: {$not: {$elemMatch: {language: "dutch"}}}},
 {translations: {$not: {$elemMatch: {language: "french"}}}},
]})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM