通过查询MongoDB组

时间:2013-08-16 06:47:47

标签: mongodb mongoose

我的收藏品包含

等记录
{ "type" : "me", "tid" : "1"  }
{ "type" : "me", "tid" : "1" }
{ "type" : "me", "tid" : "1" }
{ "type" : "you", "tid" : "1" }
{ "type" : "you", "tid" : "1" }

{ "type" : "me", "tid" : "2" }
{ "type" : "me", "tid" : "2"}
{ "type" : "you", "tid" : "2"}
{ "type" : "you", "tid" : "2" }
{ "type" : "you", "tid" : "2"}

我想要下面的结果

[
 {"tid" : "1","me" : 3,"you": 2},
 {"tid" : "2","me" : 2,"you": 3}
]

我试过小组和;聚合查询无法获得所需的结果格式。

以下是群组查询。

db.coll.group({
  key: {tid : 1,type:1},
  cond: { tid  : { "$in" : [ "1","2"]}  }, 
  reduce: function (curr,result) { 
    result.total = result.total + 1
  },
  initial: { total : 0}
})

结果就像

[
  {"tid" : "1",  "type" : "me" ,"total": 3 },
  {"tid" : "1","type" : "you" ,"total": 2 },
  {"tid" : "2", "type" : "me" ,"total": 2 },
  {"tid" : "2","type" : "you" ,"total": 3 }
]

以下是汇总查询

db.coll.aggregate([
  {$match : { "tid" : {"$in" : ["1","2"]}}},
  {$group : { _id : {tid : "$tid",type : "$type"},total : {"$sum" : 1}}}
])

给出以下结果

{ 
  "result" : 
  [
    {"_id" : {"tid" : "1","type" : "me"},"total" : 3},
    {"_id" : {"tid" : "2","type" : "me" },"total" : 2},
    {"_id" : {"tid" : "2","type" : "you"},"total" : 3}
  ]
  "ok" : 1
}

可以获得我指定的结果,或者我必须在我的代码中进行一些操作。

由于

1 个答案:

答案 0 :(得分:1)

如果您将聚合更改为:

db.so.aggregate([
    { $match : { "tid" : { "$in" : ["1", "2"] } } },

    { $group : { 
        _id : { tid : "$tid", type : "$type" }, 
        total : { "$sum" : 1 } 
    } },

    { $group : { 
        _id : "$_id.tid",
        values: { $push: { type: "$_id.type", total: '$total' } }
    } }
])

然后你的输出是:

{
    "result" : [
        {
            "_id" : "1",
            "values" : [
                { "type" : "you", "total" : 2 },
                { "type" : "me", "total" : 3 }
            ]
        },
        {
            "_id" : "2",
            "values" : [
                { "type" : "me", "total" : 2 },
                { "type" : "you", "total" : 3 }
            ]
        }
    ],
    "ok" : 1
}

虽然这与你想要的不一样,但它将是你能得到的最接近的。在您的应用程序中,您可以轻松地提取与您喜欢的相同的值,以便摆脱它。

请注意,一般情况下,您无法将值(youme)提升为 - 除非您的密钥设置有限(最多3-4项。