显示数组中仅包含特定属性的对象

问题描述 投票:0回答:1

我是mongodb的新手,如果可以的话,我想帮助我。我有如下文件(歌曲)的集合:

{
   title: 'song number 1',
   duration: '3:23',
   text: [
           {chords: 'some chords'},
           {lyrics: 'some lyrics'},
           {chords: 'again chords'},
           {lyrics: 'again lyrics'}
    ]

},
{
   title: 'song number 23',
   duration: '4:22',
   text: [
           {chords: 'some chords'},
           {lyrics: 'some lyrics'},
           {chords: 'again chords'},
           {lyrics: 'again lyrics'}
    ]

}

我只想为每个文档(歌曲)检索文本数组中的和弦。有什么想法吗?

arrays mongodb nosql bson
1个回答
0
投票

此聚合查询过滤器 text字段存在或不为空或不为null的chords数组元素。

db.test.aggregate( [
  { 
      $addFields: {
          text: { 
              $filter: {
                  input: "$text",
                     as: "txt",
                    cond: {
                             $gt: [ { $strLenCP: { $ifNull: [ "$$txt.chords", "" ] } },  0 ] 
                          }
              }
          }
      }
  }
] )

结果将如下所示(以问题帖中的第一个文档作为输入):

{
        "_id" : 1,
        "title" : "song number 1",
        "duration" : "3:23",
        "text" : [
                {
                        "chords" : "some chords"
                },
                {
                        "chords" : "again chords"
                }
        ]
}
© www.soinside.com 2019 - 2024. All rights reserved.