Arrays 显示仅包含特定属性的数组中的对象
我是mongodb的新手,如果可以的话,我愿意帮助我。我收集了如下文档(歌曲):Arrays 显示仅包含特定属性的数组中的对象,arrays,mongodb,nosql,bson,Arrays,Mongodb,Nosql,Bson,我是mongodb的新手,如果可以的话,我愿意帮助我。我收集了如下文档(歌曲): { title: 'song number 1', duration: '3:23', text: [ {chords: 'some chords'}, {lyrics: 'some lyrics'}, {chords: 'again chords'}, {lyrics: 'again lyrics'}
{
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'}
]
}
我只想从文本数组中检索每个文档(歌曲)的和弦。
有什么想法吗?此聚合查询过滤文本
数组元素,其中和弦
字段存在或不为空或不为空
db.test.aggregate( [
{
$addFields: {
text: {
$filter: {
input: "$text",
as: "txt",
cond: {
$gt: [ { $strLenCP: { $ifNull: [ "$$txt.chords", "" ] } }, 0 ]
}
}
}
}
}
] )
结果如下所示(将问题帖子中的第一个文档作为输入):
我终于明白了!我需要这个问题
db.test.aggregate([
{$unwind: "$text"},
{$match: {"text.chords":{$exists:true}}},
{$project: {'text.chords':1}}
]).pretty()
此查询仅显示每首歌曲的和弦子文档,而不显示歌词。
查询的关键(我想)是$unwind。
谢谢大家的回答和帮助。能否添加您希望检索的结果。但是,在项目中使用过滤器是过滤文档中数组元素的更有效的方法。
db.test.aggregate([
{$unwind: "$text"},
{$match: {"text.chords":{$exists:true}}},
{$project: {'text.chords':1}}
]).pretty()