Ricardo Francois
Ricardo Francois

Reputation: 792

How to conditionally copy fields from one collection and add them to another in MongoDB with PyMongo?

I've got two collections in MongoDB called collection_A and collection_B.

Essentially, I want to copy over a field from collection B given a condition in collection A but I'm not quite sure how to do this via PyMongo.

Collection Schemas:

collection_A

{
"ID": ObjectId(1234567),
"match": "yes"
}

collection_B

{
"B_ID": 1234567,
"add_field": "field_name"
}

In psuedocode, what I aim to do is:

if collection_A match = "yes":
    loop through records
    if collection_A ID = collection_B B_ID:
        add "add_field": "field_name" field to collection_A

What I have so far:

values = collection_A.find({"match": "yes})
for doc in values:
    TO-DO

I've looked around a lot on how to do this via PyMongo but was unable to find much. If anyone can help me with this problem, or direct me to useful links, that'd be helpful. Thank you

Upvotes: 0

Views: 403

Answers (1)

Belly Buster
Belly Buster

Reputation: 8834

This example copies all the required field from B to A that matches on ID. The comments explain each step.

for a_record in db.collection_A.find({'match': 'yes'}):  # Loop through collection A based on filter
    b_record = db.collection_B.find_one({'B_ID': a_record.get('ID')}, {'_id': 0, 'add_field': 1})  # Lookup corresponding record in Collection B
    if b_record is not None:  # B record will be None if no match
        db.collection_A.update_one({'_id': a_record['_id']}, {'$set': b_record})  # Update A with the value from B
    else:
        db.collection_A.update_one({'_id': a_record['_id']}, {'$set': {'add_field': None}})

Worked example with data:

from pymongo import MongoClient

db = MongoClient()['mydatabase']
  
db.collection_A.insert_one({
    "ID": 1234567,
    "match": "yes"
})

db.collection_B.insert_one({
    "B_ID": 1234567,
    "add_field": "field_name"
})

for a_record in db.collection_A.find({'match': 'yes'}):  # Loop through collection A based on filter
    b_record = db.collection_B.find_one({'B_ID': a_record.get('ID')}, {'_id': 0, 'add_field': 1})  # Lookup corresponding record in Collection B
    if b_record is not None:  # B record will be None if no match
        db.collection_A.update_one({'_id': a_record['_id']}, {'$set': b_record})  # Update A with the value from B


print(list(db.collection_A.find({})))

prints:

[{'_id': ObjectId('5fc555172bc0555f17ccb918'), 'ID': 1234567, 'match': 'yes', 'add_field': 'field_name'}]

Upvotes: 1

Related Questions