我通过pymongo使用Python3查询我的Mongodb,我很难在响应中获得特定的嵌套字段。
正确返回所有“常规”字段,但嵌套的字段返回为无。
以下是我的数据集示例:
var listeners = {};
var originalEventListener = window.addEventListener;
window.addEventListener = function(type, fn, options) {
if (!listeners[type])
listeners[type] = [];
listeners[type].push(fn);
return originalEventListener(type, fn, options);
}
var removeAllEventListener = function(type) {
if (!listeners[type] || !listeners[type].length)
return;
for (let i = 0; i < listeners[type].length; i++)
window.removeEventListener(type, listeners[type][i]);
}
这是我的python代码的一部分:
{
"_id":"5a8595ef93ccdb0f2301cf58",
"docnum":"DOC001",
"idcustomer":"CLI1",
"customername":"Ringo",
"address":[
{
"streetno":"45, First Avenue",
"cityzip":"10001 New York"
}],
"totals":[
{
"totnetamnt":66.18,
"totgrossamnt":86.034
}]
}
这是我的当前输出,嵌套字段返回为无
import pymongo
from pymongo import MongoClient
client = MongoClient()
db = client.my_database
def load_data(db):
cursor_docs = db.my_data.find(
{
" docnum " : " DOC0017133"
},
{
"idcustomer" : 1,
"docnum" : 1,
"customername" : 1,
"address.streetno" : 1,
"address.cityzip" : 1,
"totals.totnetamnt" : 1,
"totals.totgrossamnt" : 1,
}
);
#getting fields per document
for docs in cursor_docs:
docnum = docs.get("docnum")
custname = docs.get("customername")
address1 = docs.get("address.streetno")
address2 = docs.get("address.cityzip")
netamount = docs.get("totals.totnetamnt")
grossamount = docs.get("totals.totgrossamnt")
#checking field values
print('docnum : ' + str(docnum))
print('custname : ' + str(custname))
print('address1 : ' + str(address1))
print('address2 : ' + str(address2))
print('netamount : ' + str(netamount))
print('grossamount : ' + str(grossamount))
load_data(db)
这是我的预期输出,其中包含嵌套字段的实际值
docnum : DOC0017133
custname : Mary
address1 : None
address2 : None
netamount : None
grossamount : None
我尝试了不同的解决方案,但我总是将嵌套字段返回为无。
重点是:我如何只返回地址和总计的嵌套字段值(如上面的预期结果所示)?