簡體   English   中英

MongoDB獲取具有至少一個非空數組的文檔

[英]MongoDB get documents with at least one not empty array

我的架構:

    db.Interactives = mongoose.model(
        'Interactives',
        new Schema({
            url: String,
            forms: Array,
            inputs: Array,
            textareas: Array,
        })
    );

我想找到至少一個數組不為空的所有文檔,所以我嘗試了:

    await db.Interactives.find({
            $elemMatch: {
                forms: { $ne: [] },
                inputs: { $ne: [] },
                textarea: { $ne: [] },
            },
        })
            .select('-_id -__v')
            .exec()

我該如何實現?

您的代碼的問題在於,它正在嘗試確保沒有數組為空。 另一個問題是$elemMatch在數組的元素中搜索值。 您不想這樣做,想將數組與空白數組進行比較。 您唯一要做的更改是將$elemMatch替換$elemMatch $or並添加方括號,如下所示

    await db.Interactives.find({
            $or: [
                {forms: { $ne: [] }},
                {inputs: { $ne: [] }},
                {textarea: { $ne: [] }},
            ]
        })
            .select('-_id -__v')
            .exec()

您錯過的是查詢中的$or

也可以通過許多方式來完成。 假設這是您的數據集。

[
  {"Id_Cust": "4145","firstName": "Albade","language": ["English,Nepali"],"degree": []},
  {"Id_Cust": "5296","firstName": "Rafael","language": [],"degree": ["Bachelor,Masters"]},
  {"Id_Cust": "6192","firstName": "Abdul","language": [],"degree": []}
]

現在,您可以執行以下操作:

db.collection.find({
  $or: [
    {language: {$exists: true,$not: {$size: 0}}},
    {degree: {$exists: true,$not: {$size: 0}}}
  ]
})

如果數組中的字段是可選字段,請使用$exists否則可以將其排除。

選擇我

db.collection.find({
  $or: [
    {language: {$ne: []}},
    {degree: {$ne: []}}
  ]
})

如果數組中的字段是可選字段,則使用$exists ,就像上面的查詢一樣。

備選方案二

db.collection.find({
  $or: [
    {language: {$gt: []}},
    { degree: {$gt: []}}
  ]
})

如果數組中的字段是可選字段,則像在第一個查詢中一樣,請使用$exists

所有方法都提供相同的輸出

[
  {
    "Id_Cust": "4145",
    "_id": ObjectId("5a934e000102030405000000"),
    "degree": [],
    "firstName": "Albade",
    "language": [
      "English,Nepali"
    ]
  },
  {
    "Id_Cust": "5296",
    "_id": ObjectId("5a934e000102030405000001"),
    "degree": [
      "Bachelor,Masters"
    ],
    "firstName": "Rafael",
    "language": []
  }
]

因此,您可以以任何方式進行操作。

暫無
暫無

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

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