How to store query output in temp MongoDB database?

MongoDBDatabaseBig Data Analytics

For this, in a single query, simply work with forEach() and store output in a temp db. Let us first create a collection with documents −

> db.demo43.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e25d4b3cfb11e5c34d898e5")
}
> db.demo43.insertOne({"StudentName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e25d4b8cfb11e5c34d898e6")
}
> db.demo43.insertOne({"StudentName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e25d4bbcfb11e5c34d898e7")
}

Display all documents from a collection with the help of find() method −

> db.demo43.find();

This will produce the following output −

{ "_id" : ObjectId("5e25d4b3cfb11e5c34d898e5"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e25d4b8cfb11e5c34d898e6"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e25d4bbcfb11e5c34d898e7"), "StudentName" : "David" }

Following is the query to store query output in temp db −

> db.demo43.find().forEach(function(myDocument) { db.demo44.insert(myDocument); } )

Display all documents from a collection with the help of find() method −

> db.demo44.find();

This will produce the following output −

{ "_id" : ObjectId("5e25d4b3cfb11e5c34d898e5"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5e25d4b8cfb11e5c34d898e6"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e25d4bbcfb11e5c34d898e7"), "StudentName" : "David" }
raja
Published on 03-Apr-2020 12:18:58
Advertisements