我在下面有一个集合示例
//two dimensional array of spots
var spots = [[Spot]]();
//than you can store your spot arrays inside this two dimensional array
spots.append(spot2);
//accessing the spots via contentMode-Index (I would rename the contentMode to spotsIndex or something similar)
let currentSpots = spots[self.contentMode];
现在我想写一个mongodb查询,这个查询将返回isdeliver TRUE多于一个且具有相同的Order和Type 需要确切的输出
ROW Order Type isdeliver
1 T W TRUE
2 T L TRUE
3 T W TRUE
4 T L FALSE
5 C L TRUE
6 C L TRUE
7 C W TRUE
6 C W FALSE
答案 0 :(得分:1)
尝试使用此聚合按多个字段进行分组,此处我们按Order,Type和isdeliver进行分组,过滤所有数量少于两个
db.col.aggregate(
[
{$group : {
_id : {$concat : ["$Order", "$Type", "$isdeliver"]},
count : {$sum : 1},
data : {$push : "$$ROOT"}
}
},
{$match : {"count" :{ $gt : 1}}},
{$unwind : "$data"},
{ $replaceRoot: { newRoot: "$data" } }
]
)
或
db.col.aggregate(
[
{$group : {
_id : {
Order : "$Order", Type : "$Type", isdeliver : "$isdeliver"
},
count : {$sum : 1},
data : {$push : "$$ROOT"}
}
},
{$match : {"count" :{ $gt : 1}}},
{$unwind : "$data"},
{ $replaceRoot: { newRoot: "$data" } }
]
)
集合
> db.col.find()
{ "_id" : ObjectId("5a73500cd6c0ccee5268a15f"), "ROW" : 1, "Order" : "T", "Type" : "W", "isdeliver" : "TRUE" }
{ "_id" : ObjectId("5a73500cd6c0ccee5268a160"), "ROW" : 2, "Order" : "T", "Type" : "L", "isdeliver" : "TRUE" }
{ "_id" : ObjectId("5a73500cd6c0ccee5268a161"), "ROW" : 3, "Order" : "T", "Type" : "W", "isdeliver" : "TRUE" }
{ "_id" : ObjectId("5a73500cd6c0ccee5268a162"), "ROW" : 4, "Order" : "T", "Type" : "L", "isdeliver" : "FALSE" }
{ "_id" : ObjectId("5a73500cd6c0ccee5268a163"), "ROW" : 5, "Order" : "C", "Type" : "L", "isdeliver" : "TRUE" }
{ "_id" : ObjectId("5a73500cd6c0ccee5268a164"), "ROW" : 6, "Order" : "C", "Type" : "L", "isdeliver" : "TRUE" }
{ "_id" : ObjectId("5a73500cd6c0ccee5268a165"), "ROW" : 7, "Order" : "C", "Type" : "W", "isdeliver" : "TRUE" }
{ "_id" : ObjectId("5a73500cd6c0ccee5268a166"), "ROW" : 6, "Order" : "C", "Type" : "W", "isdeliver" : "FALSE" }
结果
> db.col.aggregate( [ {$group : { _id : {$concat : ["$Order", "$Type", "$isdeliver"]}, count : {$sum : 1}, data : {$push : "$$ROOT"} } }, {$match : {"count" :{ $gt : 1}}}, {$unwind : "$data"}, { $replaceRoot: { newRoot: "$data" } } ] )
{ "_id" : ObjectId("5a73500cd6c0ccee5268a15f"), "ROW" : 1, "Order" : "T", "Type" : "W", "isdeliver" : "TRUE" }
{ "_id" : ObjectId("5a73500cd6c0ccee5268a161"), "ROW" : 3, "Order" : "T", "Type" : "W", "isdeliver" : "TRUE" }
{ "_id" : ObjectId("5a73500cd6c0ccee5268a163"), "ROW" : 5, "Order" : "C", "Type" : "L", "isdeliver" : "TRUE" }
{ "_id" : ObjectId("5a73500cd6c0ccee5268a164"), "ROW" : 6, "Order" : "C", "Type" : "L", "isdeliver" : "TRUE" }
>
修改强>
在$group
db.col.aggregate(
[
{$group : {
_id : {
Order : "$Order", Type : "$Type", isdeliver : "$isdeliver"
},
count : {$sum : 1},
data : {$push : "$$ROOT"}
}
},
{$match : {$and : [{"count" :{ $gt : 1}}, {"_id.Order" : {$eq : "T"}}]}},
{$unwind : "$data"},
{ $replaceRoot: { newRoot: "$data" } }
]
)