-2

My goal is to insert a field in my database as an object using shell as below.

reviewers: Object
  reviewer1: "Alpha"
  reviewer2: "Beta"
  reviewer3: "Gamma"

I've tried several queries such as the following, but it entered the field as an array of object

db.movieDetails.update({"title": "The Martian"}, {$push:{"reviewers":{$each:[{"reviewer1":"Alpha"},{"reviewer2":"Beta"},{"reviewer3":"Gamma"}]}}})

What query would do exactly what I'm looking for?

Your input will be very helpful.

ITselect
  • 133
  • 1
  • 1
  • 10

3 Answers3

0

How about

db.movieDetails.update({"title": "The Martian"}, {"reviewers":{"reviewer1":"Alpha","reviewer2":"Beta","reviewer3":"Gamma"}})

Edit: This will replace the entire document.

Elvis
  • 1,103
  • 8
  • 15
  • 2
    no `$set` needed? – Minsky Nov 23 '20 at 19:19
  • @Visrozar thank you for your help. But when I tried, it replaced the whole document instead of inserting the field. – ITselect Nov 23 '20 at 19:26
  • 1
    @ITselect if you only want to add/edit fields to an existing document, then you should use "$set", without it, it'll replace the entire document. My bad for not understanding the question clearly. I think J.F. has written a better explanation. – Elvis Nov 23 '20 at 19:31
  • @Minsky You're right. I added $set and it did exactly the work. Thanks – ITselect Nov 23 '20 at 19:35
0

If you want to append the object to an existing one without remove the old fields you can use dot notation in this way:

db.collection.update({
  "title": "The Martian"
},
{
  "$set": {
    "reviewers.reviewer1": "Alpha",
    "reviewers.reviewer2": "Beta",
    "reviewers.reviewer3": "Gamma"
  }
})

Example here

But if you only want to set the entire object, then use $set with the object you want to insert into reviewers.

db.collection.update({
  "title": "The Martian"
},
{
  "$set": {
    "reviewers": {
      "reviewer1": "Alpha",
      "reviewer2": "Beta",
      "reviewer3": "Gamma"
    }
  }
})

Example here

J.F.
  • 13,927
  • 9
  • 27
  • 65
0

I tried the following:

db.regexPractice.update({"Employee id": 22}, {$set:{"reviewers":{"reviewer1":"Alpha","reviewer2":"Beta","reviewer3":"Gamma"}}}

And it worked correctly.

ITselect
  • 133
  • 1
  • 1
  • 10