MongoDB: Using reference as key and manually adding a value?

MongoDBBig Data AnalyticsDatabase

To manually add value, use $push in MongoDB. Let us create a collection with documents −

> db.demo585.insert({
...    firstName: 'John',
...    lastName: 'Doe',
...    SubjectName:"MongoDB",
...    Marks: [59]
... });
WriteResult({ "nInserted" : 1 })
> db.demo585.insert({
...    firstName: 'Chris',
...    lastName: 'Brown',
...    SubjectName:"MySQL",
...    Marks: [79]
... });
WriteResult({ "nInserted" : 1 })

Display all documents from a collection with the help of find() method−

> db.demo585.find();

This will produce the following output −

{ "_id" : ObjectId("5e91fd80fd2d90c177b5bcc3"), "firstName" : "John", "lastName" : "Doe", "SubjectName" : "MongoDB", "Marks" : [ 59 ] }
{ "_id" : ObjectId("5e91fd81fd2d90c177b5bcc4"), "firstName" : "Chris", "lastName" : "Brown", "SubjectName" : "MySQL", "Marks" : [ 79 ] }

Following is the query to use reference as key and manually adding a value −

> db.demo585.update({
...    firstName: 'John',
...    lastName: 'Doe',
...    SubjectName:"MongoDB",
...    Marks: [59]
... },
... {
...    "$push": {
...       "Marks": {
...          "Value": 59,
...          "Times": 3
...       }
...    }
... }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo585.find();

This will produce the following output −

{ "_id" : ObjectId("5e91fd80fd2d90c177b5bcc3"), "firstName" : "John", "lastName" : "Doe", "SubjectName" : "MongoDB", "Marks" :
   [ 59, { "Value" : 59, "Times" : 3 } 
] }
{ "_id" : ObjectId("5e91fd81fd2d90c177b5bcc4"), "firstName" : "Chris", "lastName" : "Brown", "SubjectName" : "MySQL", "Marks" : [ 79 ] }
raja
Published on 15-May-2020 10:08:20
Advertisements