【问题标题】:How to lookup data from 2 collections in MongoDB using python如何使用 python 从 MongoDB 中的 2 个集合中查找数据
【发布时间】:2019-02-28 16:11:48
【问题描述】:

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

【问题讨论】:

标签: json pymongo mongo-collection


【解决方案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

【讨论】:

    【解决方案2】:

    看看这里

    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"
                        }
                    }
                ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 2021-08-25
      相关资源
      最近更新 更多