创建一个通过组合键返回唯一结果的查询

时间:2017-04-19 14:49:05

标签: mongodb

我有这些文件:

{a: 1, b:1, c:1}
{a: 1, b:2, c:1}
{a: 1, b:1, c:2}

我需要通过类似于

的东西过滤一些东西
 _.uniqBy(documents, d => d.a + d.b);

所以结果应该是

{a: 1, b:1, c:1}
{a: 1, b:2, c:1}

我想通过mongodb本身进行过滤,之后不要出于两个原因:

  • 我使用skip属性,如果我自己过滤标签,那么我必须向skip属性添加相同数量的重复项。由于可以使用不同的跳过值调用该函数,因此我必须重新计算由于重复而删除的文档数量,并且计算成本太高

  • 我想使用相同的查询来执行model.count()

我不想修改数据,因为我还有类似model.find({c:2})的内容。数据不是真实重复,但我需要将它们视为某些任务的重复

1 个答案:

答案 0 :(得分:0)

以下是使用$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: -

此查询将提供&#34; C&#34; s的不同值的计数以及跳过的&#34; C&#34;的数量。

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 - 零表示没有重复,即只有一个&#34; C&#34;对于&#34; a&#34;和&#34; b&#34;组合

numberOfDifferentCs - &#34; C&#34; s的不同值的计数&#34; a&#34;和&#34; b&#34;组合

<强>输出: -

/* 1 */
{
    "c" : 1,
    "a" : 1,
    "b" : 2,
    "numberOfCSkipped" : 0,
    "numberOfDifferentCs" : 1
}

/* 2 */
{
    "c" : 1,
    "a" : 1,
    "b" : 1,
    "numberOfCSkipped" : 1,
    "numberOfDifferentCs" : 2
}