簡體   English   中英

有沒有辦法匹配 mongodb 子文檔數組中的 2 個特定字段值?

[英]Is there a way to match 2 specific field values in a sub-document array in mongodb?

我有以下格式的數據:

{ 
    "_id" : ObjectId("5f281caf3494701c38711e96"), 
    "WidgetId" : "0233261", 
    "Specs" : [
        {
            "WidgetType" : "A",
            "AmountLow" : NumberLong(0), 
            "AmountHigh" : NumberLong(0), 
        }, 
        {
            "WidgetType: "A",
            "AmountLow" : NumberLong(0), 
            "AmountHigh" : NumberLong(500), 
        }, 
        {
            "WidgetType" : "A"
            "AmountLow" : NumberLong(1), 
            "AmountHigh" : NumberLong(1000), 
        }
    ]
}

然而,數據是錯誤的,因為我不能有"Specs.AmountLow" = 0"Specs.AmountHigh" > 0 ,它們應該是 0/0 或 >0/>0。

我沒有找到具有"Specs.AmountLow" = 0"Specs.AmountHigh" > 0特定組合的文檔。 這是我嘗試過的兩個查詢,但沒有成功:

嘗試 1:

db.widgets.find(
    { 
        "Specs.AmountLow" : NumberLong(0), 
        "Specs.AmountHigh" : { 
            "$gt" : NumberLong(0)
        }
    }, 
    { 
        "WidgetId" : 1.0, 
        "Specs.AmountLow" : 1.0, 
        "Specs.AmountHigh" : 1.0
    }
)

上面的查詢只要AmountLow為 0 或AmountHigh大於 0 就返回所有結果,因此在示例數據中,所有數組值都匹配,即使沒有 0/> 0 值

我接下來嘗試了這個:

db.widgets.find(
    { 
        "$and" : [
            { 
                "Specs.$.AmountLow" : NumberLong(0)
            }, 
            { 
                "Specs.$.AmountHigh" : { 
                    "$gt" : NumberLong(0)
                }
            }
        ]
    }, 
    { 
        "WidgetId" : 1.0, 
        "Specs.AmountLow" : 1.0,
        "Specs.AmountHigh" : 1.0
    }
);

然而,即使我用 0/> 0 值確認了數據,這個也沒有返回任何結果

如何編寫查詢以查找AmountLow = 0AmountHigh > 0的特定子文檔組合,並且作為推論,我如何僅更新這些記錄以使其具有AmountLow = 1

預期結果:

{ 
    "_id" : ObjectId("5f281caf3494701c38711e96"), 
    "WidgetId" : "0233261", 
    "Specs" : [
        {
            "WidgetType: "A",
            "AmountLow" : NumberLong(0), 
            "AmountHigh" : NumberLong(500), 
        }
    ]
}

你可以試試,

當您使用$-positional 時,這將僅從數組和數組中返回一個匹配的文檔

  • 使用$elemMatch進行數組元素匹配
  • 在投影中的數組字段名稱后使用$ positional,
db.widgets.find({
  Specs: {
    $elemMatch: {
      AmountLow: 0,
      AmountHigh: {
        $gt: 0
      }
    }
  }
},
{
  _id: 1,
  WidgetId: 1,
  "Specs.$": 1
})

操場


您可以使用aggregate()代替上面的示例,此示例將從數組中返回所有匹配的文檔,

  • $filter根據條件從數組中獲取過濾的文檔
db.widgets.aggregate([
  {
    $addFields: {
      Specs: {
        $filter: {
          input: "$Specs",
          cond: {
            $and: [
              { $eq: ["$$this.AmountLow", 0] },
              { $gt: ["$$this.AmountHigh", 0] }
            ]
          }
        }
      }
    }
  }
])

操場

暫無
暫無

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

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