【问题标题】:PyMongo: How To Use Aggregate And Store The Results To Another Collection?PyMongo:如何使用聚合并将结果存储到另一个集合?
【发布时间】:2018-10-19 22:06:37
【问题描述】:

假设一个包含如下文档的集合:

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

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

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

但是,我想对关键字列表(超过 200 个)运行上面的 sn-p,所以我需要通过编写 Python 脚本来自动化这个过程。

问题:上面的sn-p在PyMongo中的等价物是什么?

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    以下是在 pymongo 版本 3.6.1 和 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 
    

    【讨论】:

      猜你喜欢
      • 2014-01-25
      • 1970-01-01
      • 2019-09-01
      • 2023-03-13
      • 2017-02-08
      • 2015-10-23
      • 1970-01-01
      • 2019-01-30
      • 2013-06-17
      相关资源
      最近更新 更多