Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何过滤mongoengine中的嵌入文档并获取字段值?_Python_Flask_Mongoengine - Fatal编程技术网

Python 如何过滤mongoengine中的嵌入文档并获取字段值?

Python 如何过滤mongoengine中的嵌入文档并获取字段值?,python,flask,mongoengine,Python,Flask,Mongoengine,我正在研究将交易作为嵌入文档的信用模型。以下是存储它的结构 { "_id" : ObjectId("546dae8cc09e5f0d9602e632"), "user" : ObjectId("53e7fdaac09e5f12a1230c14"), "transaction" : [ { "date" : ISODate("2014-11-20T12:34:12.878Z"), "amount" : 100

我正在研究将交易作为嵌入文档的信用模型。以下是存储它的结构

{
    "_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=“成功”)


因为你只想要上次成功存款交易的金额,所以这就可以了

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']
我所做的:
连接到本地mongodbfamily数据库,在transcollections中使用聚合函数获取嵌入文档,如果我理解正确,我在其中找到了从查询中获得的字典中的key amount值,使用嵌入文档中的字段进行查询时遇到问题。可以使用双下划线查询嵌套字段。此外,您应该使用
filter()
而不是
get()
,因为het用于只匹配单个文档的查询(如果找到多个文档,则实际会返回错误)

另外,如果您使用的是
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

谢谢,但我想用MongoEngine
  credit_obj = Credits.objects.filter(
    user=user_id,
    transaction__trans_type="deposit",
    transaction__status="success"
  ).order_by('-transaction__date').first()
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