如果我有这样的文档:
{
"_id" : ObjectId("5497b4281a78a9120872ca32"),
"title" : "Thrifty Kitchen",
"description" : "Damn ugly",
"products" : [
ObjectId("54990eeb1a78a91a5758af75"),
ObjectId("a78a91a5758af7554990eeb1"),
ObjectId("a5758af990eeb17554a78a91")
]
}
...如果(使用 pymongo)我想将此文档传递到我的网页模板,哪里是插入查询的好地方?我知道我必须执行“$in”查询才能获得这些结果,但在 ORM 世界中,我可以在模型类上编写一个方法,并只公开一个“get_products”方法。在这里,由于我的 View 逻辑直接与 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 但没有架构定义...
最佳答案
如您所料,PyMongo 的答案很简单:
resolved_products = list(mycollection.find({'_id': {'$in': result['products']}}))
MongoEngine 和其他 MongoDB ODM 提供了辅助方法来执行此类解除引用。但它们也有自己的复杂性和开销;正如我所展示的,我更喜欢直接查询相关文档。
关于python - 解析 mongoDB 引用的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27616297/