Reputation: 423
I would like to convert a document with a string like this :
{ myField : 'bar foo boo' }
Into something like this :
{ myField : ['bar', 'foo', 'boo'] }
using space as delimiter. Is it possible with aggregate or should I do it programmatically ?
Upvotes: 1
Views: 215
Reputation: 1348
You need the $split operator. It's run inside an aggregation stage. In this example we make a new field using the $project stage. To pick a specific document put a $match stage at the front of your aggregation pipeline.
> 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" ] }
>
Upvotes: 1