0

Assume a collection with documents which look like this:

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

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"}
]);

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.

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

Aventinus
  • 1,322
  • 2
  • 15
  • 33

1 Answers1

1

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 
mintekhab
  • 203
  • 1
  • 3