mongo query help using save method

27 views
Skip to first unread message

Ns Kumar

unread,
Nov 11, 2017, 4:12:07 PM11/11/17
to mongodb-user
Case1:
MongoDB Enterprise > db.coll.insert({x:1})
WriteResult({ "nInserted" : 1 })

MongoDB Enterprise > db.coll.find()
{ "_id" : ObjectId("5a0581f21ef47834e0281945"), "x" : 1 }

MongoDB Enterprise > var j = db.coll.findOne()

MongoDB Enterprise > j
{ "_id" : ObjectId("5a0581f21ef47834e0281945"), "x" : 1 }

MongoDB Enterprise > j.y=2
2

MongoDB Enterprise > j
{ "_id" : ObjectId("5a0581f21ef47834e0281945"), "x" : 1, "y" : 2 }

MongoDB Enterprise > db.coll.save(j)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

MongoDB Enterprise > db.coll.find()
{ "_id" : ObjectId("5a0581f21ef47834e0281945"), "x" : 1, "y" : 2 }

Case2:
MongoDB Enterprise > var j = db.coll.find({x:1})

MongoDB Enterprise > j
{ "_id" : ObjectId("5a0581f21ef47834e0281945"), "x" : 1, "y" : 2 }

MongoDB Enterprise > j.z=3
3

MongoDB Enterprise > db.coll.save(j)

2017-11-10T16:11:26.377+0530 E QUERY    [thread1] Error: can't save a DBQuery object :
DBCollection.prototype._validateObject@src/mongo/shell/collection.js:231:15
DBCollection.prototype._validateForStorage@src/mongo/shell/collection.js:245:5
Bulk/this.insert@src/mongo/shell/bulk_api.js:652:17
DBCollection.prototype.insert@src/mongo/shell/collection.js:344:13
DBCollection.prototype.save@src/mongo/shell/collection.js:596:16
@(shell):1:1

The only difference between case1 and case2 is the way value is stored in var j. Can someone pls help understand what is wrong in case2 that i am unable to save the document. Thanks in advance.

Kevin Adistambha

unread,
Nov 15, 2017, 11:43:45 PM11/15/17
to mongodb-user

Hi

The difference is that in case 1 you’re using db.collection.findOne() which returns a document, and in case 2 you’re using db.collection.find() which returns a cursor. See:

Since db.collection.save() expects a document as parameter, it prints an error when you called it using a cursor.

Best regards,
Kevin

Reply all
Reply to author
Forward
0 new messages