【问题标题】:Show objects from array which contain only a specific property显示数组中仅包含特定属性的对象
【发布时间】:2020-04-04 05:06:16
【问题描述】:

我是 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】:

此聚合查询过滤text 数组元素,其中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"
                }
        ]
}

【讨论】:

    【解决方案2】:

    我终于明白了!我需要这个查询

    db.test.aggregate([
        {$unwind: "$text"},
        {$match: {"text.chords":{$exists:true}}},
        {$project: {'text.chords':1}}
    ]).pretty()
    

    此查询仅显示每首歌曲的和弦子文档,不显示歌词。 查询的关键(我认为)是 $unwind。 谢谢大家的回答和帮助。

    【讨论】:

    • 不错的尝试。但是,在项目中使用过滤器是过滤文档中数组元素的更有效方法。
    猜你喜欢
    • 1970-01-01
    • 2019-03-07
    • 2021-12-08
    • 2020-01-22
    • 1970-01-01
    • 2013-02-14
    • 2012-04-28
    • 2021-08-10
    • 1970-01-01
    相关资源
    最近更新 更多