PyMongo:如何使用聚合并将结果存储到另一个集合? [英] PyMongo: How To Use Aggregate And Store The Results To Another Collection?

查看:33
本文介绍了PyMongo:如何使用聚合并将结果存储到另一个集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个包含看起来像这样的文档的集合:

Assume a collection with documents which look like this:

{
    "username" : "Aventinus"
    "text": "I love StackOverflow!",
    "tags": [
      "programming",
      "mongodb"
    ]
}

在 MongoDB 中使用 text index 和以下命令,我可以找到文本包含单词 StackOverflow 的所有文档并将它们存储在另一个集合中:

Using text index and the following command in MongoDB I can find all documents whose text contains the word StackOverflow and store them in another collection:

db.C_a.aggregate([
  {$match: {$text: {$search:"StackOverflow"}}},
  {$out:"C_b"}
]);

但是,我想为关键字列表(超过 200 个)运行上述代码段,因此我需要通过编写 Python 脚本来自动执行此过程.

However, I would like to run the above snippet for a list of keywords (more than 200) so I need to automate this process by writing a Python script.

问题:PyMongo 中上述代码段的等价物是什么?

Question: What is the equivalent of the above snippet in PyMongo?

推荐答案

以下是在 pymongo 3.6.1 和 python 3.6.4 上测试的可行代码

Following is the workable code tested on pymongo version 3.6.1 and python 3.6.4

    import pymongo
    from pymongo import MongoClient
    client = MongoClient('127.0.0.1')  # mongodb running locally
    dbRead = client['test']            # 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 

这篇关于PyMongo:如何使用聚合并将结果存储到另一个集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆