溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

mongodb如何對文檔內(nèi)數(shù)組進行過濾的方法步驟

發(fā)布時間:2020-08-20 07:24:13 來源:腳本之家 閱讀:420 作者:ZevFang 欄目:MongoDB數(shù)據(jù)庫

本文介紹了mongodb如何對文檔內(nèi)數(shù)組進行過濾的方法步驟,分享給大家,具體如下:

mongodb如何對文檔內(nèi)數(shù)組進行過濾的方法步驟

mongodb文檔內(nèi)包含數(shù)組,需要將數(shù)組中符合條件的數(shù)據(jù)過濾出來并返回結(jié)果集,可以用兩種方式來查詢group或filter。
數(shù)據(jù)源:

{
  "_id" : ObjectId("5bbcc0c9a74db9804e78a157"),
  "uid" : "1000001",
  "name" : "zhangsan",
  "addrs" : [ 
    {
      "is_query" : "1",
      "city" : "北京"
    }, 
    {
      "is_query" : "0",
      "city" : "上海"
    }, 
    {
      "is_query" : "1",
      "city" : "深圳"
    }
  ]
}
{
  "_id" : ObjectId("5bbcc167a74db9804e78a172"),
  "uid" : "1000002",
  "name" : "lisi",
  "addrs" : [ 
    {
      "is_query" : "0",
      "city" : "北京"
    }, 
    {
      "is_query" : "0",
      "city" : "上海"
    }, 
    {
      "is_query" : "1",
      "city" : "深圳"
    }
  ]
}

要求查詢指定uid下,addrs數(shù)組中只包含is_query等于1的結(jié)果集(0的不包含)。

查詢語句:

方法一:使用$unwind將addrs數(shù)組打散,獲取結(jié)果集后用$match篩選符合條件的數(shù)據(jù),最后使用$group進行聚合獲取最終結(jié)果集。

db.getCollection('user').aggregate(
  [
    {  
      $unwind: "$addrs" 
    },
    { 
      $match : {
        "uid":"1000001", 
        "addrs.is_query": "1" 
      } 
    },
    { 
      $group : { 
        "_id" : "$uid", 
        "addrs": { $push: "$addrs" } 
      } 
    } 
  ]
)

Result:

{
  "_id" : "1000001",
  "addrs" : [ 
    {
      "is_query" : "1",
      "city" : "北京"
    }, 
    {
      "is_query" : "1",
      "city" : "深圳"
    }
  ]
}

方法二:使用$match過濾符合條件的根文檔結(jié)果集,然后使用$project返回對應(yīng)字段的同時,在addrs數(shù)組中使用$filter進行內(nèi)部過濾,返回最終結(jié)果集

db.getCollection('user').aggregate(
  [
    { 
      $match : { "uid": "1000001" } 
    },
    {
      $project: {
        "uid": 1,
        "name": 1,
        "addrs": {
          $filter: {
            input: "$addrs",
            as: "item",
            cond: { $eq : ["$$item.is_query","1"] }
          }
        }
      }
    }
  ]
)

Result:

{
  "_id" : ObjectId("5bbcc0c9a74db9804e78a157"),
  "uid" : "1000001",
  "name" : "zhangsan",
  "addrs" : [ 
    {
      "is_query" : "1",
      "city" : "北京"
    }, 
    {
      "is_query" : "1",
      "city" : "深圳"
    }
  ]
}

相對于$group分組聚合返回結(jié)果集的方式,在當前查詢要求下$filter顯得更加優(yōu)雅一些,也比較直接。當然如果包含統(tǒng)計操作,比如要求返回is_query等于1的數(shù)量,這時候$group就非常合適了。

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI