在MongoDB的单个字段中连接数组中的字符串值 [英] Concatenate string values in array in a single field in MongoDB

查看:209
本文介绍了在MongoDB的单个字段中连接数组中的字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一系列具有以下格式的文件:

Suppose that I have a serie of documents with the following format:

{
    "_id": "3_0",
    "values": ["1", "2"]
}

我希望获得在单个字段中连接的数组中的值的投影。我希望获得具有以下格式的每个文档。

and I would want to obtain a projection of the values in the array concatenated in a single field. I would want to obtain each document with the following format.

{
    "_id": "3_0",
    "values": "1_2"
}

这可能吗?我试过 $ concat 但我想我不能使用 $ values 作为<$ c的数组$ c> $ concat 。

Is this possible? I have tried with $concat but I guess that I can't use $values as the array for $concat.

推荐答案

在现代MongoDB版本中您可以。您仍然无法直接将数组应用于 $ concat ,但是您可以使用 $ reduce 使用数组元素并生成:

In Modern MongoDB releases you can. You still cannot "directly" apply an array to $concat, however you can use $reduce to work with the array elements and produce this:

db.collection.aggregate([
  { "$addFields": {
    "values": { 
      "$reduce": {
        "input": "$values",
        "initialValue": "",
        "in": {
          "$cond": {
            "if": { "$eq": [ { "$indexOfArray": [ "$values", "$$this" ] }, 0 ] },
            "then": { "$concat": [ "$$value", "$$this" ] },
            "else": { "$concat": [ "$$value", "_", "$$this" ] }
          }    
        }
      }        
    }
  }}
])

当然与 $ indexOfArray 为了连接与_当它是数组的第一个索引时加下下划线。

Combining of course with $indexOfArray in order to not "concatenate" with the "_" underscore when it is the "first" index of the array.

此外,我的额外愿望已经用 $ sum回答

Also my additional "wish" has been answered with $sum:

db.collection.aggregate([
  { "$addFields": {
    "total": { "$sum": "$items.value" }
  }}
])






这种类型的聚合通常会带有一系列项目的聚合运算符。这里的区别在于它意味着在编码表示中提供的aguments的数组与当前文档中存在的数组元素相对。


This kind of gets raised a bit in general with aggregation operators that take an array of items. The distinction here is that it means an "array" of "aguments" provided in the coded representation a opposed to an "array element" present in the current document.

只有这样你可以真正做到文档中存在的数组中的项目的连接是做某种JavaScript选项,就像在 mapReduce

The only way you can really do the kind of concatenation of items within an array present in the document is to do some kind of JavaScript option, as with this example in mapReduce:

db.collection.mapReduce(
    function() {
        emit( this._id, { "values": this.values.join("_") } );
    },
    function() {},
    { "out": { "inline": 1 } }
)

当然,如果您实际上并未汇总任何内容,那么最好的方法可能就是在后处理查询结果时在客户端代码中执行加入操作。但如果需要在文档中使用它,那么mapReduce将是唯一可以使用它的地方。

Of course if you are not actually aggregating anything, then possibly the best approach is to simply do that "join" operation within your client code in post processing your query results. But if it needs to be used in some purpose across documents then mapReduce is going to be the only place you can use it.

我可以添加例如我喜欢这样的东西:

I could add that "for example" I would love for something like this to work:

{
    "items": [
        { "product": "A", "value": 1 },
        { "product": "B", "value": 2 },
        { "product": "C", "value": 3 }
    ]
}

汇总:

db.collection.aggregate([
    { "$project": {
        "total": { "$add": [
            { "$map": {
                "input": "$items",
                "as": "i",
                "in": "$$i.value"
            }}
        ]}
    }}
])

但它不起作用,因为 $ add 需要参数而不是文档中的数组。叹! :(。部分按设计推理可以说只是因为它是一个数组或列表的奇异值从转换的结果传入它不是保证那些是实际上是运算符所期望的有效奇异数值类型值。至少不是当前实现的类型检查方法。

But it does not work that way because $add expects arguments as opposed to an array from the document. Sigh! :(. Part of the "by design" reasoning for this could be argued that "just because" it is an array or "list" of singular values being passed in from the result of the transformation it is not "guaranteed" that those are actually "valid" singular numeric type values that the operator expects. At least not at the current implemented methods of "type checking".

这意味着现在我们仍然需要这样做:

That means for now we still have to do this:

db.collection.aggregate([
   { "$unwind": "$items" },
   { "$group": {
       "_id": "$_id",
        "total": { "$sum": "$items.value" }
   }}
])

还可悲的是没有应用这样的分组运算符来连接字符串的方法。

And also sadly there would be no way to apply such a grouping operator to concatenate strings either.

所以你可以希望对此进行某种改变,或希望进行一些允许外部作用域变量的改变在 $ map 以某种方式运作。更好的是,我们也欢迎新的 $ join 操作。但是这些在写作时并不存在,并且可能在一段时间内不会存在。

So you can hope for some sort of change on this, or hope for some change that allows an externally scoped variable to be altered within the scope of a $map operation in some way. Better yet a new $join operation would be welcome as well. But these do not exist as of writing, and probably will not for some time to come.

这篇关于在MongoDB的单个字段中连接数组中的字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆