Adding a specific field from a collection to an other collection, in the same DB

I have two different collections: One is Twitter_accounts where i have the info about the accounts(name, language, url…) And in the other collection is tweets_Activity. I have in it 600 tweets per acount from the first collection. In this collection (tweets_Activity)I have a field named user in that field i have two fields that i want to export to the first collection(followers and following).

I tried using aggregation but it wont update in the first collection. And i dont know how to use the pipline efficiently

Hi @Mahmoud_Bouhorma welcome to the community!

Could you post example documents from the two collections? What I understand is, you wanted to update the documents in the collection twitter_accounts using the information in the collection tweets_activity. Is this correct? Could you please post an example of the desired end result?

What have you tried so far that didn’t work?

Best regards
Kevin

Look at the $merge as it can be used to modify the origin collection:

{ $merge: {
     into: <collection> -or- { db: <db>, coll: <collection> },
     on: <identifier field> -or- [ <identifier field1>, ...],  // Optional
     let: <variables>,                                         // Optional
     whenMatched: <replace|keepExisting|merge|fail|pipeline>,  // Optional
     whenNotMatched: <insert|discard|fail>                     // Optional
} }

The pattern is $lookup from the foreign collection, $unwind , $project then the $merge

I solved it, thank you. Here is the solution:

result = tweets.aggregate([ {"$group" : {"_id": “$user.screen_name”, “followers”: {"$max" : “$user.followers_count”}}} ])

for i in result:

_id = i["_id"]

followers = i["followers"]

query = {"Twitter_handle" : _id}

aux = {"$set" : {"followers" : followers}}

accounts.update_one(query, aux)

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.