集合数据如下:
{
"_id" : ObjectId("5a28e0b6eeb0b8783a382bd0"),
"name" : "a",
"activeClass" : [
{
"status" : 0.0
},
{
"status" : 8.0
},
{
"status" : 0.0
}
]
}
{
"_id" : ObjectId("5a28e0d2eeb0b8783a382bd1"),
"name" : "b",
"activeClass" : [
{
"status" : 8.0
},
{
"status" : 8.0
},
{
"status" : 0.0
}
]
}
查询条件:
db.collection.aggregate(
{$unwind: "$activeClass" },
{$match: {"activeClass.status":8}},
{$group: {"_id": "$_id", "count": {"$sum": 1}}},
{$match: {count :{$gte :2}}}
);
返回结果:
{
"_id" : ObjectId("5a28e0d2eeb0b8783a382bd1"),
"count" : 2.0
}
解析:
unwind 是根据 $activeClass中的元素分解成单个。
查询:
db.collection.aggregate(
{$unwind: "$activeClass" }
);
返回结果:
{
"_id" : ObjectId("5a28e0b6eeb0b8783a382bd0"),
"name" : "a",
"activeClass" : {
"status" : 0.0
}
}
{
"_id" : ObjectId("5a28e0b6eeb0b8783a382bd0"),
"name" : "a",
"activeClass" : {
"status" : 8.0
}
}
{
"_id" : ObjectId("5a28e0b6eeb0b8783a382bd0"),
"name" : "a",
"activeClass" : {
"status" : 0.0
}
}
{
"_id" : ObjectId("5a28e0d2eeb0b8783a382bd1"),
"name" : "b",
"activeClass" : {
"status" : 8.0
}
}
{
"_id" : ObjectId("5a28e0d2eeb0b8783a382bd1"),
"name" : "b",
"activeClass" : {
"status" : 8.0
}
}
{
"_id" : ObjectId("5a28e0d2eeb0b8783a382bd1"),
"name" : "b",
"activeClass" : {
"status" : 0.0
}
}
集合数据:
{
"_id" : ObjectId("5a28e0b6eeb0b8783a382bd0"),
"name" : "a",
"activeClass" : [
{
"status" : 0.0
},
{
"status" : 8.0
},
{
"status" : 0.0
}
]
}
查询:返回activeClass数组第一个元素值为1的集合;
db.collection.find({activeClass.0.status: 1});