Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update multiple documents with sub array elements in mongodb without $ operator

I want to update the element of subarray with another element of same array index. Actually what mistake what I have done is typo mistake in column name (reviews, review) so want to update all reviews column with review. Can anybody give me the query to update this scenerio.

This is my document json

{
    "_id" : ObjectId("57a5df273c6c00d1378b456d"),   
    "review_time" : ISODate("2016-02-06T12:59:19.000Z"),
    "review" : "My name is Sandra P. and I am a satisfied customer. I've been working with eBrandz for a little more than two years and plan on keep doing so. They are always there whenever I have any concern and their approach is very professional. I would definitely recommend their services as I have seen great results.",
    "rating" : 5,
    "review_reply" : [ 
        {
            "author" : "http://new york.cylex usa.com/company/ebrandz inc 18441959.html",
            "reply_time" : "1969-12-31",
            "reviews" : "Sandra thanks for recommending ebrandz, appreciated."
        }, 
        {
            "author" : "http://new york.cylex usa.com/company/ebrandz inc 18441959.html",
            "reply_time" : "1969-12-31",
            "reviews" : "Sandra thanks for recommending ebrandz, appreciated.1"
        }, 
        {
            "author" : "http://new york.cylex usa.com/company/ebrandz inc 18441959.html",
            "reply_time" : "1969-12-31",
            "review" : "Sandra thanks for recommending ebrandz, appreciated22."
        }
    ],
}
like image 628
Anant Waykar Avatar asked Sep 26 '26 19:09

Anant Waykar


2 Answers

    db.temp_reviews.find( {'review_reply.reviews' : {$exists : true}  } ).forEach( function (doc) {
          doc.review_reply.forEach(function (z) {               
        if(z.reviews){        
           z.review =   z.reviews
           delete z.reviews;
        }
          });
          db.temp_reviews.save(doc);
 });
like image 183
Anant Waykar Avatar answered Sep 28 '26 09:09

Anant Waykar


Your were close, you just need to loop through your array, check if wrong field exist, create the field, delete the wrong field :

db.reviews.find({
    'review_reply.reviews': {
        $exists: true
    }
}).forEach(function(doc) {
    for (var i = 0; i < doc.review_reply.length; i++) {
        if (doc.review_reply[i].hasOwnProperty("reviews")) {
            doc.review_reply[i].review = doc.review_reply[i].reviews;
            delete doc.review_reply[i].reviews;
        }
    }
    db.reviews.save(doc);
});
like image 21
Bertrand Martel Avatar answered Sep 28 '26 09:09

Bertrand Martel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!