通过mongoDB中的键在列表内获取字典(mongoengine) [英] Getting a dictionary inside a list by key in mongoDB (mongoengine)

查看:1003
本文介绍了通过mongoDB中的键在列表内获取字典(mongoengine)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Flask应用程序(mongoengine)中使用mongoDB(mongoHQ). 我有一个Document看起来像这样:

I'm using mongoDB (mongoHQ) in my Flask app (mongoengine). I have a Document that looks like this:

{items: [{id: 1}, {id: 2}, {id: 3}]}

例如,在单个查询中是否可以通过id: 1到达dict?

Is there a way to to reach, for example, the dict with id: 1 in a single query?

目前,我正在使用next()语句遍历items列表,并且希望有一个更明智的解决方案.谢谢

Currently I'm looping through the items list with a next() statement and I was hoping for a wiser solution. Thanks

推荐答案

我对MongoEngine不熟悉,但是$ projection运算符可以过滤数组以仅显示匹配的元素.在Mongo Shell中:

I'm not familiar with MongoEngine, but the $ projection operator can filter an array to show only the matched element. In the Mongo shell:

> db.foo.insert({"items": [{"id": 1}, {"id": 2}, {"id": 3}]})
> db.foo.find({'items.id': 1}, {'items.$': true})
{ "_id" : ObjectId("51ce29b68b178484ff2a01ed"), "items" : [  {  "id" : 1 } ] }

更多信息: http://docs.mongodb.org/manual/reference/投影/位置/

您似乎在MongoEngine中做到了:

It seems in MongoEngine you do:

Foo.objects(__raw__={'items.id': 1}).only('items.$')

更多: http://mongoengine-odm. readthedocs.org/en/latest/guide/querying.html#raw-queries

这篇关于通过mongoDB中的键在列表内获取字典(mongoengine)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆