Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 }
like image 744
Daniel Avatar asked Dec 30 '25 09:12

Daniel


1 Answers

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)
like image 144
mickl Avatar answered Jan 01 '26 09:01

mickl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!