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 }
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)