我的收藏是这样的:
{
"_id" : ObjectId("590886af47627f86e5857141"),
"code" : "MY",
"pre_title" : "republic of",
"name" : "Malaysia",
"topics" : [
{
"name" : "overview",
"body" : "ergergerg123234",
"type" : "info",
"_id" : ObjectId("5931243d26fca3496dbffe92"),
"facts" : [
{
"key" : "capital",
"value" : "Kuala Lumpur",
"_id" : ObjectId("5931243d26fca3496dbffe96")
},
{
"key" : "population",
"value" : "232424234",
"_id" : ObjectId("5931243d26fca3496dbffe95")
},
{
"key" : "reliogion",
"value" : "Islam",
"_id" : ObjectId("5931243d26fca3496dbffe94")
},
{
"key" : "government_form",
"value" : "Federal constitutional monarchy",
"_id" : ObjectId("5931243d26fca3496dbffe93")
}
]
},
{
"name" : "Good to know",
"body" : "here in good to know",
"type" : "info",
"_id" : ObjectId("5931243d26fca3496dbffe90"),
"facts" : [
{
"key" : "key1",
"value" : "value1",
"_id" : ObjectId("5931243d26fca3496dbffe91")
}
]
}
]
}
我需要访问topicId =“X”和countryId = _id的主题。我写这行但结果是错误的:所以它有两个条件。第一个countryId应匹配然后TopicId
var query = {"_id":_id,"topics.$._id": topicId }
Country.findOne(query ,function (err, topic) {
console.log('topic',topic);
})
更新:
它的工作方式与此类似,但我还需要了解key = {XX}
的内容Country.findById(query).select({ topics: { $elemMatch: { _id: topicId }
} }).
.then((topic,err) => {
答案 0 :(得分:0)
var query = {"_id":_id,"topics._id": topicId }
Country.findOne(query,{topics.$:1} ,function (err, topic) {
console.log('topic',topic);
})
从查询中删除$使用topic._id而不是主题。$ ._ id