Merge Two Mongodb Collections and select unique values (pymongo)

Viewed 98

I have a collection of questions , and a collection of sales in both collections i have a field called item_id

I need to generate a list with the unique items id on each collection

Example :

orders collection :

{
"orderid": 1
"itemid": item1
},
{
"orderid": 2
"itemid": item2
},
{
"orderid": 3
"itemid": item4
}

questions collection :

{
"questionid":1
"itemid":item1
},
{
"questionid":2
"itemid":item2
},
{
"questionid":3
"itemid":item3
}

The result im looking for is something like this

items collection :

{
"itemid":item1,
"itemid":item2,
"itemid":item3,
"itemid":item4,
}
1 Answers

Get distinct items from collection by using: col.distict('itemid')

And then aggregate items in a set data structure.

all_items = set()
orders = db.orders.distinct('itemid')
questions = db.questions.distinct('itemid')
for item in orders:
    all_items.add(item)
for item in questions:
    all_items.add(item)

At the end all_items is a set containing distinct items from both collections and you can convert it to any other data structure as you need.

#inserting to item collection
col = db.items
for item in all_items:
    col.insert_one({'item' : item})

Adding items to a set, guarantees uniqueness of elements.

Related