mongodb如何對文檔內數(shù)組進行過濾的方法步驟
本文介紹了mongodb如何對文檔內數(shù)組進行過濾的方法步驟,分享給大家,具體如下:
mongodb文檔內包含數(shù)組,需要將數(shù)組中符合條件的數(shù)據(jù)過濾出來并返回結果集,可以用兩種方式來查詢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的結果集(0的不包含)。
查詢語句:
方法一:使用$unwind將addrs數(shù)組打散,獲取結果集后用$match篩選符合條件的數(shù)據(jù),最后使用$group進行聚合獲取最終結果集。
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過濾符合條件的根文檔結果集,然后使用$project返回對應字段的同時,在addrs數(shù)組中使用$filter進行內部過濾,返回最終結果集
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分組聚合返回結果集的方式,在當前查詢要求下$filter顯得更加優(yōu)雅一些,也比較直接。當然如果包含統(tǒng)計操作,比如要求返回is_query等于1的數(shù)量,這時候$group就非常合適了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Windows下把MongoDB安裝為系統(tǒng)服務的方法
這篇文章主要介紹了Windows下把MongoDB安裝為系統(tǒng)服務的方法,本文詳細介紹了將mongoDB安裝為WinXP下系統(tǒng)服務的過程,需要的朋友可以參考下2014-10-10