collection
/* 1 */
{
"_id" : ObjectId("5c89fb827f5cc02498908c53"),
"item" : "journal",
"tags" : [
{
"id" : 1.0,
"name" : "blank"
},
{
"id" : 2.0,
"name" : "red"
}
]
}
/* 2 */
{
"_id" : ObjectId("5c89fb827f5cc02498908c54"),
"item" : "mat",
"tags" : [
{
"id" : 1.0,
"name" : "gray"
},
{
"id" : 2.0,
"name" : "blank"
},
{
"id" : 3.0,
"name" : "blank"
}
]
}
/* 3 */
{
"_id" : ObjectId("5c89fb827f5cc02498908c55"),
"item" : "mousepad",
"tags" : [
{
"id" : 1.0,
"name" : "gel"
},
{
"id" : 2.0,
"name" : "blue"
}
]
}
1
使用mongo查詢一個(gè)對(duì)象數(shù)組中元素屬性為特定值的數(shù)據(jù),期望查詢結(jié)果為:
/* 1 */
{
"_id" : ObjectId("5c89fb827f5cc02498908c53"),
"tags" : []
}
/* 2 */
{
"_id" : ObjectId("5c89fb827f5cc02498908c54"),
"tags" : [
{
"id" : 2.0,
"name" : "blank"
},
{
"id" : 3.0,
"name" : "blank"
}
]
}
/* 3 */
{
"_id" : ObjectId("5c89fb827f5cc02498908c55"),
"tags" : []
}
語(yǔ)句:
db.test.aggregate(
[
{
$project:{
tags:{
$filter:{
input:"$tags",
as:"tag",
cond:{$eq:["$$tag.name", "blank"]}
}
}
}
},
{
$project:{
tags:{
$filter:{
input:"$tags",
as:"tag",
cond:{$gte:[{$size:"$tags"}, 2]}
}
}
}
}
])
2
若想得到每條數(shù)據(jù)里tags中name=blank的數(shù)據(jù)個(gè)數(shù),語(yǔ)句為:
db.test.aggregate(
[
{
$project:{
tags:{
$filter:{
input:"$tags",
as:"tag",
cond:{$eq:["$$tag.name", "blank"]}
}
}
}
},
{
$project:{
count:{
$size: "$tags"
}
}
}
])
結(jié)果為:
/* 1 */
{
"_id" : ObjectId("5c89fb827f5cc02498908c53"),
"count" : 1
}
/* 2 */
{
"_id" : ObjectId("5c89fb827f5cc02498908c54"),
"count" : 2
}
/* 3 */
{
"_id" : ObjectId("5c89fb827f5cc02498908c55"),
"count" : 0
}
3
若想取count=2的數(shù)據(jù),語(yǔ)句:
db.test.aggregate(
[
{
$project:{
tags:{
$filter:{
input:"$tags",
as:"tag",
cond:{$eq:["$$tag.name", "blank"]}
}
}
}
},
{
$project:{
count:{
$size: "$tags"
}
}
},
{
$match:{
count:2
}
}
])
效果:
/* 1 */
{
"_id" : ObjectId("5c89fb827f5cc02498908c54"),
"count" : 2
}
好的mongo聚合查詢博客: