Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into an array of substrings or characters in MongoDB

I need to convert fields like this:

{ 
    "_id" : ObjectId("576fd6e87d33ed2f37a6d526"), 
    "phoneme" : "JH OY1 N Z" 
}

into an arrays of substrings like this

{ 
    "_id" : ObjectId("576fd6e87d33ed2f37a6d526"), 
    "phonemes" : [ "JH", "OY1", "N", "Z" ] 
}

and sometimes into an array of characters like this

{
    "_id" : ObjectId("576fd6e87d33ed2f37a6d526"), 
    "phonemes" : ["J", "H", " ", "O", "Y", "1", " ", "N", " ", "Z"]
}

I found some code here which converts a string into an array, but it's a bit too simple for my purposes as there is only a single array element to be created.

db.members.find().snapshot().forEach( function (x) {
   x.photos = [{"uri": "/images/" + x.photos}];
   db.members.save(x);
 });

Is the entire javascript language available to me from within mongo shell statements?

like image 790
Max Hodges Avatar asked Nov 17 '14 05:11

Max Hodges


People also ask

How can I split a string into an array of substrings?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do I separate data in MongoDB?

In MongoDB, the $split aggregation pipeline operator divides a string into an array of substrings based on a delimiter. The delimiter is removed from the string, and the substrings are added as elements to the array. To use $split , you specify the string and the delimiter.

How do I split a collection in MongoDB?

When you shard a collection that has existing data, MongoDB automatically creates chunks to evenly distribute the collection. To split data effectively in a sharded cluster you must consider the number of documents in a chunk and the average document size to create a uniform chunk size.

What is split in MongoDB?

Definition. Divides a string into an array of substrings based on a delimiter. $split removes the delimiter and returns the resulting substrings as elements of an array. If the delimiter is not found in the string, $split returns the original string as the only element of an array.


1 Answers

Much easier than I thought. Just use JavaScript split function. boom!

db.temp.find().snapshot().forEach( function (el) {
el.phonemes = el.phoneme.split(' ');
db.temp.save(el);
});
like image 167
Max Hodges Avatar answered Oct 16 '22 13:10

Max Hodges