首页 > 解决方案 > 在特定集合中查找子文档

问题描述

我想在特定集合(名称:国家)中查找子文档(关键字)。 猫鼬 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);
    }

}

标签: mongoose

解决方案


    db.collection.aggregate([
  {
    "$unwind": "$keywords"
  },
  {
    "$match": {
      "keywords._id": ObjectId("5f626eb337fd4d75ab694108")
    }
  },
  {
    "$project": {
      name: "$keywords.name"
    }
  }
])

检查结果mongoplayground


推荐阅读