3

I'm fairly new to node js and mongoDB and I need to add or update a Subdocument on mongodb collection as follow :

{
    "_id": "58286e49769e3729e895d239",
    "id": "2",
    "title": "Session Title",
    "sessiondate": "2016-02-11T21:00:00.000Z",
    "startTime": "14:30",
    "endTime": "16:30",
    "breakStartTime": "16:30",
    "breakEndTime": "18:00",
    "talks": [
        {
            "id": "3",
            "title": "Android",
            "speaker": {
                "id": "1",
                "name": "john doe",
                "about": "about the speaker",
                "photo": "https://pbs.twimg.com/profile_images/566353055788978177/dUy_ueY2.jpeg"
            }
        }
    ]
}

All the solutions I have found is using mongoose, where in this specific project we decided not to use mongoose, any thoughts?

2 Answers 2

9

To add or update a new talk in the embedded document, you can use any of the atomic update operators depending on how many documents in the collection you want to update. For a single atomic update, use the updateOne() method as in the following example:

1. Adding a new subdocument

// Example of adding a subdocument to an existing document.

var MongoClient = require('mongodb').MongoClient,
    ObjectId = require('mongodb').ObjectId;

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

    // Get a collection
    var collection = db.collection('mycollection');

    // The new talk document to be added 
    var doc = {
        "id": "4",
        "title": "PyData",
        "speaker": {
            "id": "7",
            "name": "alice bob",
            "about": "about the speaker",
            "photo": "https://pbs.twimg.com/dUy_ueY2.jpeg"
        }
    };

    // Update the document with an atomic operator
    collection.updateOne(
        { "_id": ObjectId("58286e49769e3729e895d239") },
        { "$push": { "talks": doc } },
        function(err, result){
            console.log(result);
            db.close();
        }
    )

});

In the above, you use the $push operator to append the specified document to an array of embedded documents (talks field).


2. Updating an existing subdocument

// Example of updating an existing subdocument.

var MongoClient = require('mongodb').MongoClient,
    ObjectId = require('mongodb').ObjectId;

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

    // Get a collection
    var collection = db.collection('mycollection');

    // Update the document with an atomic operator
    collection.updateOne(
        { 
            "_id": ObjectId("58286e49769e3729e895d239"),
            "talk.id": "3"
        },
        { "$set": { 
            "talks.$.title": "Android version 7.0",
            "talks.$.speaker.name": "foo bar"
        } },
        function(err, result){
            console.log(result);
            db.close();
        }
    )

});

With an existing document update, you apply the $set operator together with the $ positional operator in your update operation to change the embedded document fields. The $ positional operator will identify the correct element in the array to update without explicitly specifying the position of the element in the array. For this to work, the array field must appear as part of the query document, hence the query

{ 
    "_id": ObjectId("58286e49769e3729e895d239"),
    "talk.id": "3" // <-- array field is part of the query
}
Sign up to request clarification or add additional context in comments.

Comments

0

Take a look at Node.JS MongoDB driver

Basic example

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Grid = require('mongodb').Grid,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

  // Set up the connection to the local db
  var mongoclient = new MongoClient(new Server("localhost", 27017), {native_parser: true});

  // Open the connection to the server
  mongoclient.open(function(err, mongoclient) {

    // Get the first db and do an update document on it
    var db = mongoclient.db("integration_tests");
    db.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
      assert.equal(null, err);
      assert.equal(1, result);

      // Get another db and do an update document on it
      var db2 = mongoclient.db("integration_tests2");
      db2.collection('mongoclient_test').update({a:1}, {b:1}, {upsert:true}, function(err, result) {
        assert.equal(null, err);
        assert.equal(1, result);

        // Close the connection
        mongoclient.close();
      });
    });
  });

2 Comments

Thank you for the clarification, however I don't get exactly what {a:1}, {b:1} means , and the same thing appears in the documentation mongodb.github.io/node-mongodb-native/api-generated/… , I'm really dump!
As my example shows, I need to add a new talk or update an existing one.

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.