我是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'}
]
}
我只想为每个文档(歌曲)检索文本数组中的和弦。有什么想法吗?
此聚合查询过滤器 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"
}
]
}