我可以将带有 space 分隔符的字符串字段转换为 mongoDB 聚合中的数组吗

Can I convert a string field with space delimiter into array in mongoDB aggregate

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

{ myField : 'bar foo boo' }

变成这样的东西:

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

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

您需要 $split 运算符。它在聚合阶段中 运行。在这个例子中 我们使用聚合管道前端的 $project stage. To pick a specific document put a $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" ] }
>