本文介绍了mongo 组查询如何保留字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家.在 mongo 组查询中,结果仅显示参数中的键.如何像mysql查询组一样保留每个组中的第一个文档.例如:

-------------------------------------------------------------------------|姓名 |年龄 |性 |省|城市 |地区|地址 |-------------------------------------------------------------------------|第一个 |22 |纯爷们|北京 |北京 |朝阳 |青年路 ||第一个 |24 |纯爷们|北京 |北京 |徐辉 |赵家帮||24k |220 |... |.... |... |... |... |-------------------------------------------------------------------------db.users.group({key: { name: 1},reduce: function ( curr, result ) { result.count ++ },initial: {count : 0 } })

结果:

[{"name" : "ddl1st",计数":1},{"name" : "24k",计数":1}]

如何获得以下内容:

[{"name" : "ddl1st",年龄":22,"sex" : "纯爷们","省" : "北京","city" : "北京","区域" : "朝阳","address" : "青年路",计数":1},{"name" : "24k",年龄":220,"性别": "...",省" : "...",城市" : "...",区域" : "...",地址" : "...",计数":1}]
解决方案

如果你想保留每个组的第一个匹配条目的信息,你可以尝试聚合如下:

 db.test.aggregate([{$组:{_id : '$name',名称 : { $first: '$name' },年龄 : { $first: '$age' },性别 : { $first: '$sex' },省 : { $first: '$province' },城市 : { $first: '$city' },区域 : { $first: '$area' },地址 : { $first: '$address' },计数 : { $sum: 1 },}}]);

Everybody.In mongo group query, the result shows only the key(s) in arguments. How to keep the first document in each group like mysql query group.for example:

-------------------------------------------------------------------------
|  name  | age  |  sex  | province |   city   |   area   |   address     |
-------------------------------------------------------------------------
| ddl1st | 22   | 纯爷们 |  BeiJing |  BeiJing | ChaoYang | QingNianLu    |
| ddl1st | 24   | 纯爷们 |  BeiJing |  BeiJing | XuHui    | ZhaoJiaBangLu |
|  24k   | 220  | ...   |  ....    |  ...     | ...      | ...           |
-------------------------------------------------------------------------



db.users.group({key: { name: 1},reduce: function ( curr, result ) { result.count ++ },initial: {count : 0 } })

result:

[
{
    "name" : "ddl1st",
    "count" : 1
},
{
    "name" : "24k",
    "count" : 1
}
]

How to get the following:

[
   {
   "name" : "ddl1st",
   "age" : 22,
   "sex" : "纯爷们",
   "province" : "BeiJing",
   "city" : "BeiJing",
   "area" : "ChaoYang",
   "address" : "QingNianLu",
   "count" : 1
   },
   {
   "name" : "24k",
   "age" : 220,
   "sex" : "...",
   "province" : "...",
   "city" : "...",
   "area" : "...",
   "address" : "...",
   "count" : 1
}
]
解决方案

If you want to keep the information about the first matching entries for each group, you can try aggregating like:

    db.test.aggregate([{
      $group: {
         _id : '$name',
         name : { $first: '$name' },
         age : { $first: '$age' },
         sex : { $first: '$sex' },
         province : { $first: '$province' },
         city : { $first: '$city' },
         area : { $first: '$area' },
         address : { $first: '$address' },
         count : { $sum: 1 },
      }
    }]);

这篇关于mongo 组查询如何保留字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:07