Dorra Lazheri
Dorra Lazheri

Reputation: 11

inserting the result of a mongo db query in a new collection

i want to store the result of a mongo db query in a new collection but i have this error : uncaught exception: can't save a DBQuery object.

this is my code :

var com=db.comments.find({message: /http/ })   
db.com_filtre.insert(com);

the variable com isn't empty. when i try com.size(): i have 50 elements.

Upvotes: 1

Views: 3172

Answers (2)

Yathish Manjunath
Yathish Manjunath

Reputation: 2029

find() method returns a cursor to the resultSet. hence u need to fetch the documents from the cursor as below :

 var cur = db.comments.find({message: /http/});
 while( cur.hasNext() )
  {
    db.com_filtre.insert( cur.next() );
  }

Upvotes: 1

Blakes Seven
Blakes Seven

Reputation: 50406

The result of .find() is a "Cursor" and not a plain object. You either convert it via .toArray()

var com=db.comments.find({message: /http/ }).toArray()   
db.com_filtre.insert(com);

Or get a singular object:

var com=db.comments.findOne({message: /http/ })
db.com_filtre.insert(com);

It depends if you want to insert "many" matches or a single document.

Upvotes: 4

Related Questions