0

I am using pymongo to update some data in a mongodb. I am trying to use aggregate and lookup to combine data from two collections into one. Basically I am trying to do something like this: https://stackoverflow.com/a/35948843

Here is my code:

client = pymongo.MongoClient('localhost', 27017) #Connecting to mongo
db = client['<Database name>'] 
collection = db["<Collection name 1>"]

collection.aggregate([{
    "$lookup": {
            "from": "<Collection name 2>",
            "localField": "Symbol",
            "foreignField": "Symbol",
            "as": "Extra Info"
        }
}])

While I am not getting any error, I see that my collection has not been updated and the aggregation hasn't worked

I tried to output the result of the aggregation to check if there's any error:

results = collection.aggregate([{
    "$lookup": {
            "from": "<Collection name 2>",
            "localField": "Symbol",
            "foreignField": "Symbol",
            "as": "Extra Info"
        }
}])
print (list(results))

The output of the "results" comes out to be exactly what I want which means the aggregation has worked.

So I am trying to understand what I am doing wrong or stupid? If anyone could help that would be really helpful.

pg100
  • 5
  • 4
  • The aggregation query returns a cursor - it doesn't update a collection.. – prasad_ Jun 15 '20 at 10:12
  • Are you trying to store the aggregation results in one of the original collections, or a new collection? – Joe Jun 15 '20 at 17:59
  • Ideally I would like to store it in the original collection only and delete the other collection – pg100 Jun 16 '20 at 01:16

1 Answers1

0

I was making a trivial mistake. As mentioned in one of the comments, $lookup only returns a cursor and doesn't actually updates the collection. To update or create a new collection, $out can be a good option. Here is the code:

client = pymongo.MongoClient('localhost', 27017) #Connecting to mongo
db = client['<Database name>'] 
collection = db["<Collection name 1>"]

collection.aggregate([{
    "$lookup": {
            "from": "<Collection name 2>",
            "localField": "Symbol",
            "foreignField": "Symbol",
            "as": "Extra Info"
        }
{"$unwind": "$Extra_info"},
{"$out" : "<Collection name 3>" }}])

Note: $unwind is used to deconstruct an array inside the document. Documentation here: https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

pg100
  • 5
  • 4