本文介绍了MongoDB – 如何返回带有 <field_value> 的文档作为<field_key>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过一些研究,我已经看到了通过 mongoDB 的 $mapReduce 功能解决这个问题的方法,但是我还没有设法让它工作......这是我正在处理的:

[{_id: '1',device_id: 'ML39A-341D4-UI041',日期:'2018-03-28T00:00:00.000Z'},{_id: '2',device_id: 'ML39A-341D4-UI041',日期:'2018-03-29T00:00:00.000Z'},{_id: '3',device_id: 'D4YK2-R2D20-KYPI9'日期:'2018-04-01T00:00:00.000Z'}]

聚合后的预期结果应该是这样的:

[{'ML39A-341D4-UI041':['2018-03-28T00:00:00.000Z','2018-03-29T00:00:00.000Z']},{'D4YK2-R2D20-KYPI9':['2018-04-01T00:00:00.000Z']}]
解决方案

您可以通过使用 $group 对文档进行分组的聚合框架来实现此目的device_id,后跟一个 arrayToObject 以获取一个值作为键:

查询如下所示:

db.collection.aggregate([{$组":{"_id": "$device_id",DT":{"$push": "$date"}}}, {$replaceRoot":{新根":{$arrayToObject":{"$concatArrays": [[{"k": "$_id",v":$dt"}]]}}}}])

结果:

[{D4YK2-R2D20-KYPI9":[2018-04-01T00:00:00.000Z"]},{ML39A-341D4-UI041":["2018-03-28T00:00:00.000Z",2018-03-29T00:00:00.000Z"]}]

您可以在这里尝试:mongoplayground.net/p/t9AjMA0nXCn

After some research I've seen ways to go around this through mongoDB's $mapReduce feature, however I haven't managed to get it working.. Here's what I'm dealing with:

[
  {
    _id: '1',
    device_id: 'ML39A-341D4-UI041',
    date: '2018-03-28T00:00:00.000Z'
  },
  {
    _id: '2',
    device_id: 'ML39A-341D4-UI041',
    date: '2018-03-29T00:00:00.000Z'
  },
  {
    _id: '3',
    device_id: 'D4YK2-R2D20-KYPI9'
    date: '2018-04-01T00:00:00.000Z'
  }
]

The expected result after aggregation should look like this:

[
  {
    'ML39A-341D4-UI041': [
      '2018-03-28T00:00:00.000Z',
      '2018-03-29T00:00:00.000Z'
    ]
  },
  {
    'D4YK2-R2D20-KYPI9': [
      '2018-04-01T00:00:00.000Z'
    ]
  }
]
解决方案

You can achieve this with the aggregation framework using a $group to group documents by device_id, followed by a arrayToObject to get a value as key:

the query looks like this:

db.collection.aggregate([{
  "$group": {
    "_id": "$device_id",
    "dt": {
      "$push": "$date"
    }
  }
}, {
  "$replaceRoot": {
    "newRoot": {
      "$arrayToObject": {
        "$concatArrays": [
          [{
            "k": "$_id",
            "v": "$dt"
          }]
        ]
      }
    }
  }
}])

results:

[
  {
    "D4YK2-R2D20-KYPI9": [
      "2018-04-01T00:00:00.000Z"
    ]
  },
  {
    "ML39A-341D4-UI041": [
      "2018-03-28T00:00:00.000Z",
      "2018-03-29T00:00:00.000Z"
    ]
  }
]

you can try it here: mongoplayground.net/p/t9AjMA0nXCn

这篇关于MongoDB – 如何返回带有 <field_value> 的文档作为<field_key>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 23:18