从mongodb中的其他集合创建新集合

时间:2019-02-18 20:11:56

标签: mongodb pymongo

假设我有一个这样的收藏集:

{ "_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 }

我如何仅使用具有“副本”字段的文档来生成新集合,以获得这样的新集合:

{ "_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 }

1 个答案:

答案 0 :(得分:3)

您可以使用$out运算符根据汇总结果创建新集合,请尝试:

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

db.collection.aggregate(pipeline)