简体   繁体   English

MongoDB将[{k1:v1},{k2:v2}]转换为{v1:v2}

[英]MongoDB transform [{k1:v1},{k2:v2}] into {v1: v2}

I have a collection with the following schema: 我有一个具有以下架构的集合:

// ----- SOURCE SCHEMA ----- //

{
    "_id" : ObjectId("5564e8937c32c85f03ea028a"),
    "sku" : "MD01"
},
{
    "_id" : ObjectId("5564e8c97c32c85f03ea028b"),
    "sku" : "MD02"
},
{
    "_id" : ObjectId("5564e8dd7c32c85f03ea028c"),
    "sku" : "MD03"
}

// ----- SOURCE SCHEMA ----- //

Now I want to transform these documents into the following format: 现在,我想将这些文档转换为以下格式:

// ----- DESIRED FORMAT ----- //

{
    "5564e8dd7c32c85f03ea028c": "MD01",
    "5564e8c97c32c85f03ea028b": "MD02",
    "5564e8dd7c32c85f03ea028c": "MD03"
}

// ----- DESIRED FORMAT ----- //

Currently I have to use two for loop in server side javascript for this task, but I think it will face performance problems if the collection going bigger. 目前,我必须在服务器端javascript中使用两个for loop来完成此任务,但是我认为如果集合变大,它将面临性能问题。

So how can I archive this by using only Mongodb queries ? 那么如何only Mongodb queries使用only Mongodb queries存档? Is the performance of this approach better? 这种方法的性能更好吗?

Using Map-Reduce you can achieve the desired output: 使用Map-Reduce可以实现所需的输出:

// map each object to { "XXXXXXXX": sku }
map = function() {
  obj = {}
  obj[this._id.valueOf()] = this.sku
  emit(null, obj)
}

// Aggregate all objects in one (very?) big one
// by copying individual properties
reduce = function(key, values) {
  result = {}
  for (idx in values) {
    for (k in values[idx]) {
      result[k] = values[idx][k]
    }
  }

  return result
}

Producing: 生产:

> db.test.mapReduce(map, reduce, {out: {inline:1}}).results
[
    {
        "_id" : null,
        "value" : {
            "5564e8937c32c85f03ea028a" : "MD01",
            "5564e8c97c32c85f03ea028b" : "MD02",
            "5564e8dd7c32c85f03ea028c" : "MD03"
        }
    }
]

That being said, this is not efficient and will eventually hit the 16M limit as you are in fact requesting an aggregation of all your DB objects in one document only. 话虽这么说,但这并不是很有效,最终将达到16M的限制,因为实际上您仅要求将所有 DB对象聚合到一个文档中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM