0

我有包含类似记录的集合

{ "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
}

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

谢谢

4

1 回答 1

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
}

尽管这与您想要的不同,但它将是您可以获得的最接近的。在您的应用程序中,您可以轻松地提取与您想要从中获取的值相同的

请记住,通常您不能将值 ( you, me) 提升为- 除非您的键是有限集合(最多 3-4 项)。

于 2013-08-16T08:52:18.583 回答