Daniel
Daniel

Reputation: 395

Create a new collection from other collection in mongodb

Suposse I have a Collection like this:

{ "_id" : 8751, "title" : "The Banquet", "author" : "Dante" }
{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 }
{ "_id" : 8645, "title" : "Eclogues", "author" : "Dante" }
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 }
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }

How can I generate a new collection with only the documents that have the field "copies", to get a new collection like this:

{ "_id" : 8752, "title" : "Divine Comedy", "author" : "Dante", "copies" : 1 }
{ "_id" : 7000, "title" : "The Odyssey", "author" : "Homer", "copies" : 10 }
{ "_id" : 7020, "title" : "Iliad", "author" : "Homer", "copies" : 10 }

Upvotes: 3

Views: 1565

Answers (2)

camposer
camposer

Reputation: 5622

That didn't work for me using mongoshell, in my case I finally used:

cur = db.original_collection.find();
while (cur.hasNext()) { db.backup_collection.insert(cur.next()) }

Upvotes: 0

mickl
mickl

Reputation: 49985

You can use $out operator to create a new collection based on aggregation results, try:

pipeline = [
    { $match: { copies: { $exists: true } } }
    { $out: "newCollectionName" }
]

db.collection.aggregate(pipeline)

Upvotes: 5

Related Questions