6

I need to update a document in an array inside another document in Mongo DB

    {
            "_id" : ObjectId("51cff693d342704b5047e6d8"),
            "author" : "test",
            "body" : "sdfkj dsfhk asdfjad ",
            "comments" : [
                    {
                            "author" : "test",
                            "body" : "sdfkjdj\r\nasdjgkfdfj",
                            "email" : "[email protected]"
                    },
                    {
                            "author" : "hola",
                            "body" : "sdfl\r\nhola \r\nwork here"
                    }
            ],
            "date" : ISODate("2013-06-30T09:12:51.629Z"),
            "permalink" : "jaiho",
            "tags" : [
                    "jaiho"
            ],
            "title" : "JAiHo"
    }


Q1) Update email of 0th element of comments array
db.posts.update({"permalink" : "haha"},{$set:{"comments.0.email":1}})
This doesn't throw any exception but doesn't update anything as well
Q2) Add a field on nth element of comments array number_likes
db.posts.update({"permalink" : "haha"},{$inc:{"comments.0.num_likes":1}})
Doesn't work either.

Am I missing something here?
3
  • 2
    Lol, this is almost certainly from the 10gen mongo course :P education.10gen.com/courses Commented Aug 1, 2013 at 14:41
  • 1
    Yeah actually, but couldn't find what went wrong with the solution and didn't wanted to fail the test ;) You may look at it as cheating but may be I'm still learning. Commented Aug 13, 2013 at 16:29
  • Nah, its all good. It just made me laugh. Commented Aug 14, 2013 at 0:26

2 Answers 2

8

Q1: If you update with permalink 'jaiho' instead of 'haha', it most certainly updates the email;

> db.posts.update({"permalink" : "jaiho"},{$set:{"comments.0.email":1}})
> db.posts.find()
    ...,    "email" : 1 },...

Q2: Same goes for this include;

> db.posts.update({"permalink" : "jaiho"},{$inc:{"comments.0.num_likes":1}})
> db.posts.find()
    ..., "num_likes" : 1 },...
Sign up to request clarification or add additional context in comments.

Comments

6

If you are trying to do it dynamically in Node JS following should work.

i = 0;
selector = {};
operator = {};
selector['comments.' + i + '.email'] = 1; // {'comments.0.num_likes' : 1}
operator['$inc'] = selector;  // {'$inc' : {'comments.0.num_likes' : 1} }
db.posts.update({'permalink' : 'xyz'}, operator);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.