我是mongodb的新手。我只是使用mongodb启动我的项目。在我的项目中,我需要从嵌套数组中获取数据。我知道有太多与此相关的问题,但我的问题没有解决。这是json。
{
"_id": ObjectId("58805a04469d401ab45943f6"),
"siteId": 2,
"guardGender": "MALE",
"checkoutPoint": [{
"_id": ObjectId("588098a025bad12cf01936d6"),
"title": "string",
"nfcCheckoutPoint": [{
"_id": ObjectId("5880c14683d042207896f7a4"),
"title": "yup",
"intervalTime": "string",
}]
}]
}
我只需要nfcCheckoutPoint数组。
"nfcCheckoutPoint": [{
"_id": ObjectId("5880c14683d042207896f7a4"),
"title": "yup",
"intervalTime": "string",
}]
这是我正在使用的代码
var criteria = {
_id: payloadData.siteId,
"checkoutPoint._id": payloadData.routeId,
"checkoutPoint.nfcCheckoutPoint._id": payloadData.checkpointId
};
var projection = { nfcCheckoutPoint: { $elemMatch: { _id: payloadData.checkpointId }}}
var option = {
lean: true
};
Service.SiteService.getSite(criteria, projection, option, function (err, data) {
if (err) {
cb(err)
} else {
console.log(data)// this give me wrong values
}
})
var getSite = function (criteria, projection, options, callback) {
options.lean = true;
Models.Site.find(criteria, projection, options, callback);
};
我得到这个代码:
{ "_id": ObjectId("58805a04469d401ab45943f6")}
答案 0 :(得分:0)
您可以尝试使用aggregate
查询
db.getCollection('products').aggregate([
{ "$match": { _id: payloadData.siteId} }, //siteId = ObjectId("58805a04469d401ab45943f6")
{ "$project": {
"checkoutPoint": {
"$filter": {
"input": {
"$map": {
"input": "$checkoutPoint",
"as": "cPoint",
"in": {
"_id": "$$cPoint._id",
"nfcCheckoutPoint": {
"$filter": {
"input": "$$cPoint.nfcCheckoutPoint",
"as": "nfcPoint",
"cond": {
"$eq": [ '$$nfcPoint._id', payloadData.checkpointId ] //checkpointId = ObjectId("5880c14683d042207896f7a4")
}
}
}
}
}
},
"as": "checkoutPoint",
"cond": { "$eq": [ "$$checkoutPoint._id", payloadData.routeId]}// routeId =ObjectId("588098a025bad12cf01936d6")
}
}
}},
{$project:{nfcCheckoutPoint:{$arrayElemAt: [ "$checkoutPoint.nfcCheckoutPoint", 0 ]}, _id:0}}
])
然后输出将如下:
{
"nfcCheckoutPoint" : [
{
"_id" : ObjectId("5880c14683d042207896f7a4"),
"title" : "yup",
"intervalTime" : "string"
}
]
}