mongoose - 在特定集合中查找子文档
问题描述
我想在特定集合(名称:国家)中查找子文档(关键字)。 猫鼬 5.10.8
{
"name" : "jobs",
"keywords" : [...],
...
},
{
"name" : "countries",
"keywords" : [
{
"active" : true,
"_id" : ObjectId("5f626eb337fd4d75ab694108"),
"name" : "japan"
},
{
"active" : true,
"_id" : ObjectId("5f626eb337fd4d75ab694109"),
"name" : " france"
}
],
}
我需要检索国家名称,例如:法国,比利时我试过了,但没有结果:
async function getCountryName(id_country){
try{
const result = await Dictionary
.find({name: 'countries'})
.where('keywords.id').equals(id_country)
.select('name')
.exec()
console.log(result);
} catch(e){
console.log(e);
}
}
解决方案
db.collection.aggregate([
{
"$unwind": "$keywords"
},
{
"$match": {
"keywords._id": ObjectId("5f626eb337fd4d75ab694108")
}
},
{
"$project": {
name: "$keywords.name"
}
}
])
检查结果mongoplayground
推荐阅读
- hadoop - 当端口未打开时,是否可以通过 nginx 进行端口转发?
- c - 如何修复 - 使用 getchar() 和 do-while 的意外输出
- java - 无法加载 PySpark ALS 模型
- javascript - 流:结合精确的对象类型
- python - 如何在 python 中使用 pika (RabbitMQ) 向消费者添加多处理
- android - 从谷歌播放更新后应用程序不断崩溃
- dataframe - 将 dict 中的键值对分配给 DataDrame 在 Julia 1.1 中不起作用
- javascript - 与基于类的方法相比,在使用 Hooks 设置状态后重新渲染时有什么区别?
- java - Sparkpost:向同一地址/ Java API 发送电子邮件
- javascript - 这段代码中当前和历史的价值是什么。请解释一下