Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB: Using reference as key and manually adding a value?
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 ] }Advertisements