Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving the result of a MongoDB query

When doing a research in mongo shell I often write quite complex queries and want the result to be stored in other collection. I know the way to do it with .forEach():

db.documents.find(query).forEach(function(d){db.results.insert(d)})

But it's kind of tedious to write that stuff each time. Is there a cleaner way? I'd like the syntax to be something like db.documents.find(query).dumpTo('collectionName').

like image 941
vorou Avatar asked Dec 25 '13 06:12

vorou


People also ask

What does save () in MongoDB return?

The save() returns a WriteResult() object that contains the status of the insert or update operation.

How MongoDB data is stored?

MongoDB is a NoSQL Server in which data is stored in BSON (Binary JSON) documents and each document is essentially built on a key-value pair structure. As MongoDB easily stores schemaless data, make it appropriate for capturing data whose structure is not known.

What is $$ in MongoDB?

The $map has parameters - input which specifies the array field name, as specifies the current array element identifier in an iteration, and in where each array element is processed in the iteration. Within the in , the current array element is referred using the $$ prefix - this is the syntax required.


2 Answers

Here's a solution I'll use: db.results.insert(db.docs.find(...).toArray())

There is still too much noise, though.

UPD: There is also an option to rewrite find using aggregation pipeline. Then you can use $out operator.

like image 58
vorou Avatar answered Oct 23 '22 14:10

vorou


It looks like you are doing your queries from the mongo shell, which allows you to write code in javascript. You can assign the result of queries to a variable:

result = db.mycollection.findOne(my_query)

And save the result to another collection:

db.result.save(result)

You might have to remove the _id of the result if you want to append it to the result collection, to prevent a duplicate key error

Edit:

db.mycollection.findOne({'_id':db.mycollection.findOne()['_id']})
db.foo.save(db.bar.findOne(...))

If you want to save an array, you can write a javascript function. Something like the following should work (I haven't tested it):

function save_array(arr) {
    for(var i = 0; i < arr.length; i++) {
        db.result.save(arr[i])
    }
}

...

result = db.mycollection.find(...)
save_array(result)

If you want the function to be available every time you start mongo shell, you can include it in your .mongorc.js file

like image 32
Mzzl Avatar answered Oct 23 '22 14:10

Mzzl