如何将多个 MongoDB 记录中的字符串结果连接成 MongoDB 中的单个结果? [英] How to concatenate string results from multiple MongoDB records into a single result in MongoDB?

查看:12
本文介绍了如何将多个 MongoDB 记录中的字符串结果连接成 MongoDB 中的单个结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有以下记录:

{ text: "foo"},
{ text: "bar"}

我怎样才能得到这样的结果:

How can I get a result such as:

results: "foo bar"

我最接近它的是使用 $addToSet 但这只是创建一个包含结果的数组,而不是我真正想要的单个字符串.

The closest I am getting to it is to use $addToSet but this just creates an array with the results instead of a single string which is what I really want.

results: [ "foo", "bar" ] 

使用 Mongo 3.4

Using Mongo 3.4

推荐答案

使用 $group 从所有文档中获取一个数组,然后 $reduce$concat 得到一个字符串:

Use $group to get an array from all the documents and then $reduce with $concat to get one string:

db.col.aggregate([
    {
        $group: {
            _id: null,
            text: { $push: "$text" }
        }
    },
    {
        $project: {
            text: {
                $reduce: {
                    input: "$text",
                    initialValue: "",
                    in: {
                        $cond: [ { "$eq": [ "$$value", "" ] }, "$$this", { $concat: [ "$$value", " ", "$$this" ] } ]
                    }
                }
            }
        }
    }
])

$group 之后,您将获得包含所有 text 值的数组的单个文档.然后 $reduce 扫描"数组并将状态 ($$value) 与当前处理的项目连接起来.对于第一项状态将是一个空字符串,所以我使用 $cond 来避免开头有空格.

After $group you will get single document which contains an array of all text values. Then $reduce "scans" the array and concatenates the state ($$value) with currently processed item. For the first item state will be an empty string so I'm using $cond to avoid having whitespace on the beginning.

这篇关于如何将多个 MongoDB 记录中的字符串结果连接成 MongoDB 中的单个结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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