MongoDB:从已创建记录中的字段获取值

2skhul33  于 2023-01-12  发布在  Go
关注(0)|答案(1)|浏览(142)

我是MongoDB的新手,我用的是MongoDB 6.0.3和MongoDB指南针1.34.2。
我有一个数据库的数据:

{
    "id": 123,
    "attr": [
        {"name": "Some Name 1", "val": "Some value"},
        {"name": "Some Name 2", "val": "blabla"},
        {
            "name": "Need Find",
            "val": "I Need This Value"
        },
        {"name": "Nevermind", "val": "3.14"}
    ]
},
{
    "id": 33333,
    "attr": [
        {"name": "Some Name 1", "val": "Some value"},
        {"name": "Some Name 2", "val": "blabla"},
        {
            "name": "Need Find",
            "val": "I Need This Value but ID is not match"
        },
        {"name": "Nevermind",   "val": "3.14"}
    ]
}

因此,我通过查询查找记录:

db.myTable.find({'id' : '123', 'attr' : { $elemMath : {'name' : 'Need Find'}} })

这将返回一条完整的记录。
如何只返回具有字段"val"的值(或仅值)的字段?
举例说明我的需求:

"val": "I Need This Value"

或:

"I Need This Value"

我只需要通过查询返回一个字段值或已找到记录的字段值。

pod7payv

pod7payv1#

解决方案:

db.collection.aggregate({
  $match: {
    "id": 1,
    "attr.name": "Need Find"
  }
},
{
  $unwind: "$attr"
},
{
  $match: {
    "attr.name": "Need Find"
  }
},
{
  "$project": {
    "_id": 0,
    "attr.val": 1
  }
})

相关问题