如何使用python在MongoDB中查找2个集合中的数据

时间:2018-09-25 05:48:05

标签: json pymongo mongo-collection

我需要在Python中从MongoDB中读取2个集合数据,有什么方法可以在python中联接数据?

2 个答案:

答案 0 :(得分:1)

假设我们有两个集合(表):

  1. buy_orders
  2. sell_orders

这些表具有相同的字段'id_transaction',我们希望将这些表联接到该字段上:

import pymongo


my_client = pymongo.MongoClient('mongodb://localhost:27017/')
my_db = my_client['Orders']
my_collection = my_db['buy_orders']
result = my_collection..aggregate([ {'$lookup' : {'from': sell_orders','localField': 'id_transaction','foreignField': 'id_transaction','as': 'results' }}])

要打印结果:

for item in result:
    print(item)

有关更多参考:MongoDB DocsPyMongo Docs

答案 1 :(得分:0)

在这里看看

from bson.objectid import ObjectId

#the custom_id for reference
custom_id = ObjectId()

#creating user with the role admin
db.users.insert_one({"name": "Boston", "role_id": custom_id})

#Creating role with the custom id
db.roles.insert_one({"_id": custom_id, "name": "Admin")}

#lookup usage
db.users.aggregate([
                {
                    "$lookup":
                    {
                        "from": "roles",
                        "localField": "role_id",
                        "foreignField": "_id",
                        "as": "roles"
                    }
                }
            ])