Search code examples
mongodbmongo-shell

How to print/use save() data result mongo shell


I am adding a record in a collection from mongo shell, and its adding successfully,

var demoData = db.getCollection('demoCollection').save({
    "name": "My Name",
    "about": "About my self",
    "createdAt": new Date(Date.now()).toISOString()
}); 

I want to use that above added record _id in another operation, but i am not able to print result of demoData or demoData._id,

I tried below options,

print(demoData._id); // returns '[unknown type]'
printJson(demoData); // Not printing
printJson(demoData.toArray()); // Not printing

Solution

  • save returns a WriteResult. Try:

    MongoDB Enterprise ruby-driver-rs:PRIMARY> x={a:1}
    { "a" : 1 }
    
    MongoDB Enterprise ruby-driver-rs:PRIMARY> db.foo.save(x)
    WriteResult({ "nInserted" : 1 })
    
    MongoDB Enterprise ruby-driver-rs:PRIMARY> x
    { "a" : 1, "_id" : ObjectId("5f04601ac17c40d26f231e47") }