1

I have below query, in 2nd query I get null for que.name.

var que  = db.que.find({ _id: u.que_id }, {name:1})
db.documents.update(u, {$set: {que_name: que.name}})

I can see data for que as below

 { "_id" : "general", "name" : "General" }

but no data for que.name. What's wrong?

1
  • what are you trying to achieve actually? transfer name attribute of que collection to documents collection as que_name ? Commented Aug 20, 2013 at 13:42

2 Answers 2

2

find returns cursor to the matching documents. So que is not a single document - it is cursor. Cursor do not have field name - that's why you have no data for que.name. Cursor points to documents which you have found (yes, there could be several documents). If you will iterate over cursor, you will get each document. Just to show what is cursor:

var que  = db.que.find({ _id: u.que_id }, { name: 1 }) // que is a cursor
que.forEach(function(d) { print(d.name); })

If you want to get document, then use findOne method, which returns one document matching your search criteria:

var que  = db.que.findOne({ _id: u.que_id }, { name: 1 }) // now que is document
que.name // prints name value
Sign up to request clarification or add additional context in comments.

Comments

1

db.collection.find returns a cursor. Try using findOne()

var que = db.que.findOne( { _id: u.que_id }, {name:1})

2 Comments

That is exactly what I wrote 0_o
Excuse me i didn't refresh before posting... I didn't remove it after i saw your post because i think mine is smaller and more concise. If you think i should remove it, i can, but in no way i copied your answer. (MongoDB documentation is no secret)

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.