0

I have the below collection with the name sample_collection.

{'_id': ObjectId('603e9cc2784fa0d80d8672cd'),
'name': 'balaji',
'**B**': [{'price': 1, 'price_range': 'G'},
 {'price': 6, 'price_range': 'F'},
 {'price': 4, 'price_range': 'C'}]}

and I have one array with name A = [{'price': 22, 'price_range': 'X'}, {'price': 33, 'price_range': 'U'} ]

I am trying to merge the elements of the array A to the array with name B which is part of the above collection with the below pymongo query.

db.sample_collection.update_one({"name": "balaji"}, {"$addToSet": {"B": A}})

However, I see that the array as a whole is getting merged with the above collection, as shown below.

[{'_id': ObjectId('603e9cc2784fa0d80d8672cd'),
'name': 'balaji',
'B': [{'price': 1, 'price_range': 'G'},
{'price': 6, 'price_range': 'F'},
{'price': 4, 'price_range': 'C'},
[{'price': 22, 'price_range': "X"}
{'price': 33, 'price_range': 'U'}]]} (we can see another square brackets for 22 and 33)

however I need the elements of the array A(but not the array itself) to be merged with the collection array B and the expected result needs to be

[{'_id': ObjectId('603e9cc2784fa0d80d8672cd'),
'name': 'balaji',
'B': [{'price': 1, 'price_range': 'G'},
{'price': 6, 'price_range': 'F'},
{'price': 4, 'price_range': 'C'},
{'price': 22, 'price_range': "X"}
{'price': 33, 'price_range': 'U'}} (here there are no square brackets for elements with price 22 and 33)

May I know the query for the above please.

3
  • 1
    Take a look at $each Commented Mar 4, 2021 at 8:49
  • @Joe ok sure :) Commented Mar 4, 2021 at 12:10
  • @Joe, thanks it works, if possible, please add this comment in answer, it might help others as well. Commented Mar 6, 2021 at 7:09

1 Answer 1

1

To $push or $addToSet the individual members of an array, use the $each operator with update, such as:

db.sample_collection.update_one({"name": "balaji"}, {"$addToSet": {"B": {$each: A}}})

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.