簡體   English   中英

Java Mongodb 找到符合條件的過濾器子數組

[英]Java Mongodb find filter sub array with condition

我有一個 mongo 數據庫集合,我只想過濾嵌套數組

{
    "_id" : "E00001",
    "name" : "Ramu",
    "totoList" : [
        {
            "mandatory" : false,
            "description" : "call customer care"
        },
        {
            "mandatory" : true,
            "description" : "get bill from person"
        }
    ]
}

我使用這段代碼,我得到了整個集合

List<Employee> empList = mongoTemplate.find(query, Employee.class);

我想要一個 output 過濾掉 mandatory: false,只需要過濾嵌套數組

這是我的預期結果

{
    "_id" : "E00001",
    "name" : "Ramu",
    "totoList" : [
        {
            "mandatory" : true,
            "description" : "get bill from person"
        }
    ]
}

如果員工沒有任何強制性待辦事項,我仍然希望 output 作為

{
    "_id" : "E00001",
    "name" : "Ramu"
}

我不想完全過濾掉員工,只需要過濾嵌套數組

我經歷了$unset $pull everything belongs to update但我想在find中實現這個

一種選擇是使用$filter ,但如果不匹配,它會給你[]

db.collection.aggregate([
  {$set: {
      totoList: {
        $filter: {
          input: "$totoList",
          cond: "$$this.mandatory"
        }
      }
  }}
])

playground 示例中查看它是如何工作的

如果刪除該字段很重要,您可以為其添加另一個步驟:

  {$replaceRoot: {
      newRoot: {$cond: [
          {$gt: [{$size: "$totoList"}, 0]},
          "$$ROOT",
          {_id: "$_id", name: "$name"}
      ]}
  }}

playground 示例中查看它是如何工作的

暫無
暫無

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

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