本文介紹了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就非常合適了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- 分布式文檔存儲數(shù)據(jù)庫之MongoDB訪問控制的操作方法
- 分布式文檔存儲數(shù)據(jù)庫之MongoDB備份與恢復的實踐詳解
- 分布式文檔存儲數(shù)據(jù)庫之MongoDB分片集群的問題
- SpringDataMongoDB多文檔事務的實現(xiàn)
- MongoDB中文檔的更新操作示例詳解
- MongoDB數(shù)據(jù)庫文檔操作方法(必看篇)
- mongodb 數(shù)據(jù)類型(null/字符串/數(shù)字/日期/內嵌文檔/數(shù)組等)
- PHP庫 查詢Mongodb中的文檔ID的方法
- MongoDB如何更新多級文檔的數(shù)據(jù)