【问题标题】:Pattern to resolve mongoDB references解决 mongoDB 引用的模式
【发布时间】:2015-02-21 08:32:03
【问题描述】:

如果我有这样的文件:

{
    "_id" : ObjectId("5497b4281a78a9120872ca32"),
    "title" : "Thrifty Kitchen",
    "description" : "Damn ugly",
    "products" : [
        ObjectId("54990eeb1a78a91a5758af75"),
        ObjectId("a78a91a5758af7554990eeb1"),
        ObjectId("a5758af990eeb17554a78a91")
    ]
}

...如果(使用 pymongo)我想将此文档传递给我的网页模板,那么哪里是插入查询的好地方呢?我知道我必须执行“$in”查询才能获得这些结果,但在 ORM 世界中,我可以在模型类上编写一个方法并公开一个“get_products”方法。在这里,由于我的视图逻辑直接与 Mongo 交互并且中间没有 ORM,处理这些分辨率的常见做法或模式是什么?

result = mongo.db.mycollection.find_one({"_id": ObjectId(collection_id)})
# wish it could be
for product in result.products:
    print product.myattribute # but that will only return the ObjectId

# would you do something like this?
result.resolved_products = ... # do stuff to resolve ObjectIds

而且,我还没有在我的谷歌搜索中看到它,但是有没有人将查询嵌入到类的方法中,以便您可以向结果对象添加功能?有点像使用 ORM 但没有架构定义...

【问题讨论】:

    标签: python mongodb flask pymongo


    【解决方案1】:

    如您所料,PyMongo 的答案很简单:

    resolved_products = list(mycollection.find({'_id': {'$in': result['products']}}))
    

    MongoEngine 和其他 MongoDB ODM 提供了辅助方法来执行这种取消引用。但是它们有自己的复杂性和开销。正如我所展示的,我更喜欢直接查询相关文档。

    【讨论】:

    • 感谢您提供示例。关于我关于包装类的问题,我想可能有那些“自己动手”的,但 ODM 可能首当其冲。就个人而言,我也喜欢直接查询的简单性。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-10-03
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    相关资源
    最近更新 更多