pymongo how to combine these document in different collection using aggregate documenta…
- User
pymongo how to combine these document in different collection using aggregate document_a = { "project_id" : "ABC123", "20232211" : { "atc" : 1 }} document_b = { "project_id" : "ABC123", "20232211" : { "atc" : 2 }} into document_c = { "project_id" : "ABC123", "20232211" : { "atc" : 1, "atc_doc_b": 2 }}
- Assistant
To combine documents from different collections in MongoDB using the PyMongo driver, you can use the Aggregate framework with the
$lookuppipeline stage. Here's an example of how to achieve this:from pymongo import MongoClient # Assuming you have already connected to MongoDB client = MongoClient('mongodb://localhost:27017/') db = client['your_database_name'] # Assuming you have two collections named 'collection_a' and 'collection_b' collection_a = db['collection_a'] collection_b = db['collection_b'] # Aggregation pipeline pipeline = [ { '$match': { 'project_id': 'ABC123' } # Filter documents by project_id }, { '$lookup': { 'from': 'collection_b', 'localField': 'project_id', 'foreignField': 'project_id', 'as': 'document_b' } }, { '$addFields': { '20232211.atc_doc_b': { '$arrayElemAt': ['$document_b.20232211.atc', 0] } } }, { '$project': { 'document_b': 0 } } ] # Perform aggregation result = collection_a.aggregate(pipeline) # Print the result for doc in result: print(doc)