这是this问题的延续。
我使用以下代码查找其文字包含单词C_a
的集合StackOverflow
中的所有文档,并将其存储在另一个名为C_b
的集合中:
import pymongo
from pymongo import MongoClient
client = MongoClient('127.0.0.1') # mongodb running locally
dbRead = client['C_a'] # using the test database in mongo
# create the pipeline required
pipeline = [{"$match": {"$text": {"$search":"StackOverflow"}}},{"$out":"C_b"}] # all attribute and operator need to quoted in pymongo
dbRead.C_a.aggregate(pipeline) #execution
print (dbRead.C_b.count()) ## verify count of the new collection
但是,如果我为多个关键字运行相同的代码段,结果会被覆盖,这非常有用。例如,我希望集合C_b
包含包含关键字StackOverflow
,StackExchange
和Programming
的所有文档。为此,我只需使用上述关键字迭代代码段。但不幸的是,每次迭代都会覆盖前一次。
问题:如何 更新 输出集合而不是覆盖它?
加号:是否有一种聪明的方法可以避免重复,或者之后我是否必须检查重复项?
答案 0 :(得分:2)
如果您查看文档$out
并不支持更新
https://docs.mongodb.com/manual/reference/operator/aggregation/out/#pipe._S_out
所以你需要做两个阶段的操作
pipeline = [{"$match": {"$text": {"$search":"StackOverflow"}}},{"$out":"temp"}] # all attribute and operator need to quoted in pymongo
dbRead.C_a.aggregate(pipeline)
然后使用
中讨论的方法https://stackoverflow.com/a/37433640/2830850
dbRead.C_b.insert(
dbRead.temp.aggregate([]).toArray()
)
在开始运行之前,您需要删除C_b
集合