0

In my database.collection i.e. db.blog.posts I am trying to add a key and value that itself has multiple keys and values.

Current collection:

db.blog.posts.findOne()
"title":"blog posts"

I tried using $set, $push but nothing seems to work.

This also didn't work when I tried adding single collection:

db.blog.posts.updateOne({"title":"blog posts"}, {"$set":{"comments":[{"comment":"good post", "author":"john","votes":0}]}})

Nor insertOne instead of updateOne and I even tried with:

var myEmployee=[
{"comment":"good post", "author":"john", "votes":0},
{"comment":"i thought it was too short", "author":"claire","votes":3},
{"comment":"free watches", "author":"claire","votes":-1},
];
db.blog.posts.insert(myEmployee)

This is what I want:

"title" : "A blog post",
"comments" : [
    {
        "name" : "joe",
        "email" : "[email protected]",
        "content" : "nice post."
    },
    {
        "name" : "bob",
        "email" : "[email protected]",
        "content" : "good post."
    }
]

1 Answer 1

1

The updateOne command you have should have created an array for comments with a single entry. If you wanted multiple entries, you can just add multiple objects to the array in the update. The $set operator will change the value of the key to what you set as the second parameter.

db['blog.posts'].updateOne({"title":"blog posts"}, {
  "$set": {
    "comments":[
      {
        "name" : "joe",
        "email" : "[email protected]",
        "content" : "nice post."
      },
      {
        "name" : "bob",
        "email" : "[email protected]",
        "content" : "good post."
      }
    ]
  }
})

If you want to add additional items to the comments, this can be done with $push. The $push operator adds to the array.

db['blog.posts'].updateOne({"title":"blog posts"}, {
  "$push": {
    "comments": {
      "comment": "good post",
      "author": "john",
      "votes": 0
    }
  }
})

Docs for $set
Docs for $push

NB the examples above are for a collection named 'blog.posts' rather than a database named 'blog' and a collection names 'posts'. Ideally, brackets should be used for the property accessor where the collection name is not a valid JavaScript identifier although the dot notation in the question still works.

Sign up to request clarification or add additional context in comments.

1 Comment

ahhhhh...my mistake was i was adding square brackets after each sub key-value pairs and thanks for correcting that. Second problem was, i was not using the right code to display. To display multiple lines i was using db.blog.posts.findOne() instead of posts.find()

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.