【问题标题】:Can I convert a string field with space delimiter into array in mongoDB aggregate我可以将带有空格分隔符的字符串字段转换为mongoDB聚合中的数组吗
【发布时间】:2020-09-01 01:36:17
【问题描述】:

我想用这样的字符串转换一个文档:

{ myField : 'bar foo boo' }

变成这样:

{ myField : ['bar', 'foo', 'boo'] }

使用空格作为分隔符。 是否可以聚合或我应该以编程方式进行?

【问题讨论】:

  • 我相信你应该以编程方式进行。

标签: arrays string mongodb aggregate field


【解决方案1】:

您需要$split 运算符。它在聚合阶段内运行。在这个例子中 我们使用$project 阶段创建一个新字段。要选择特定文档,请将 $match 阶段放在聚合管道的前面。

> use test
switched to db test
> db.test.insert({ myField : 'bar foo boo' })
WriteResult({ "nInserted" : 1 })
> db.test.aggregate([{"$project" :{ "mySplitField" :{"$split" : ["$myField", " "]}}}])
{ "_id" : ObjectId("5ebe77d0ca404d65eed0c4a8"), "mySplitField" : [ "bar", "foo", "boo" ] }
>

【讨论】:

    猜你喜欢
    • 2015-06-02
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2011-08-31
    • 2019-08-23
    • 2021-01-22
    相关资源
    最近更新 更多