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

问题描述 投票:2回答:1

假设我有一个这样的集合:

{ "_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 }
mongodb pymongo
1个回答
3
投票

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

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

db.collection.aggregate(pipeline)
© www.soinside.com 2019 - 2024. All rights reserved.