user4119502
user4119502

Reputation:

merge two fields in document using mongodb

Below is my JSON, is there any way where I can merge multiple fields of a same document.

 "_id" : 1,
 "sem" : 1,
 "achieve" : [ 70, 87, 90 ] 

I am expecting the output as

 "_id" : 1,
 "sem" : [1,70, 87, 90],
 "achieve" : [ 70, 87, 90 ] 

Upvotes: 0

Views: 604

Answers (1)

Viraj
Viraj

Reputation: 357

One of the simple methods just to achieve what you are asking. You can create a loop for all the documents of the collection though. The code below has 'stack' collection having just one document, the one you mentioned.

doc = db.stack.findOne();
var tmp = doc.sem;
doc.sem = new Array();
doc.sem.push(tmp);
i = 0;
for(i = 0;i<doc.achieve.length;i++){
    doc.sem.push(doc.achieve[i]);
}
db.stack.update({sem:1},doc);

Upvotes: 1

Related Questions