下面是使用$group
和$project
查询。
db.collection.aggregate([
{$group : {
_id : { a : "$a" , b : "$b" } ,
count: { $sum : 1 },
c : {$first : "$c"}}},
{$project : {"_id" : 0, a: "$_id.a", b : "$_id.b", "c" : 1}}
]);
输出: -
/* 1 */
{
"c" : 1,
"a" : 1,
"b" : 2
}
/* 2 */
{
"c" : 1,
"a" : 1,
"b" : 1
}
方法2: -
该查询将得到的 “C” S和的 “C” 的号码不同的值的计跳过。
db.collection.aggregate([
{$group : {
_id : { a : "$a" , b : "$b" } ,
count: { $sum : 1 },
c : {$first : "$c"}}},
{$project : {"_id" : 0, a: "$_id.a", b : "$_id.b", "c" : 1,
"numberOfCSkipped" : {$cond: {if : { $gt : ["$count", 1] }, then : {$subtract: ["$count", 1]}, else : 0 }},
"numberOfDifferentCs" : "$count" }}
]);
numberOfCSkipped - 零表示不存在重复,即只有一个 “C” 为 “a” 和 “b” 的组合
numberOfDifferentCs - 的 “C” 不同的值的计数S表示“ a”和 “b” 的组合
输出: -
/* 1 */
{
"c" : 1,
"a" : 1,
"b" : 2,
"numberOfCSkipped" : 0,
"numberOfDifferentCs" : 1
}
/* 2 */
{
"c" : 1,
"a" : 1,
"b" : 1,
"numberOfCSkipped" : 1,
"numberOfDifferentCs" : 2
}
你是否试图在每个键的唯一组合中跳过'douments?或者只是最终的输出。 [$跳过](https://docs.mongodb.com/manual/reference/operator/aggregation/skip/)做后者。 – Veeram