如何在mongoengine中过滤EmbeddedDocument并获得字段的值?

时间:2014-11-21 08:53:09

标签: python flask mongoengine

我正在使用Credits模型,将事务作为嵌入文档。以下是存储它的结构。

{
    "_id" : ObjectId("546dae8cc09e5f0d9602e632"),
    "user" : ObjectId("53e7fdaac09e5f12a1230c14"),
    "transaction" : [ 
        {
            "date" : ISODate("2014-11-20T12:34:12.878Z"),
            "amount" : 100,
            "follow_num" : "d5571d91-e434-4b10-bbd8-2a6511e78011",
            "memo" : "test1",
            "trans_type" : "deposit",
            "status" : "success"
        }, 
        {
            "date" : ISODate("2014-11-20T13:03:49.851Z"),
            "amount" : 500,
            "follow_num" : "2fd57cf4-eb5d-4751-9c88-6158adda6572",
            "memo" : "test2",
            "trans_type" : "withdraw",
            "status" : "failed"
        }, 
        {
            "date" : ISODate("2014-11-20T22:54:19.892Z"),
            "amount" : 20,
            "follow_num" : "c2bd7dd2-3b17-41c2-9513-60a058a5622a",
            "memo" : "test3",
            "trans_type" : "deposit",
            "status" : "success"
        }
    ]
}

我想要检索上次成功存款交易的金额 (即transaction.trans_type ="存款"和transaction.status ="成功")。

@property
def last_deposit(self):
    credit_obj = Credits.objects.get(user=self,
                               transaction__match={"trans_type":"deposit","status":"success"})

2 个答案:

答案 0 :(得分:1)

由于您只想要上次成功存款交易的金额,这将完成这项工作

import pymongo

c=pymongo.Connection(host="localhost",port=27017)

db=c["family"]

i= db.tran.aggregate([ { "$unwind":"$transaction"}, {"$match": {"$and":[{"transaction.status":"success" , "transaction.trans_type":"deposit"}]}},{"$sort":{"date":-1}},{"$limit":1}])

a=i["result"]

a=a[0]

b=a['transaction']

print b['amount']

我做了什么:         连接到 trans 集合中的本地mongodb 系列数据库确实聚合函数以获取嵌入式文档,其中我从查询中获取的字典中找到了键值的值

答案 1 :(得分:1)

如果我理解正确,您在使用嵌入式文档中的字段进行查询时遇到问题。您可以使用双下划线来查询嵌套字段。此外,您应该使用filter()而不是get(),因为它仅适用于只匹配单个文档的查询(如果找到多个文档,实际上会返回错误)。

  credit_obj = Credits.objects.filter(
    user=user_id,
    transaction__trans_type="deposit",
    transaction__status="success"
  ).order_by('-transaction__date').first()

此外,如果您使用get(),则应该捕获可能的例外情况。

from mongoengine.errors import DoesNotExist, MultipleObjectsReturned
from bson.errors import InvalidId

try:
  credit_obj = Credits.objects.get(
    user=user_id,
  )

# verify that user_id is a valid ObjectID
except InvalidId:
  print "Not a valid ObjectId: '%s'." % str(user_id)
  # code to handle error

except DoesNotExist, e:
  print "Could not get '%s'. Error: %s" % (user_id, e)
  # code to handle error

except MultipleObjectsReturned:
  print "Multiple objects matched query."
  # code to handle error