我有一个文件如下:
{
user: 'hvt07',
photos: [
{
link: 'http://link.to.com/image1.jpg',
isPrivate: true
},
{
link: 'http://link.to.com/image2.jpg',
isPrivate: false
}
]
}
我想获取所有带有的照片:
isPrivate: false
我正在使用以下查询:
db.collection_name.find({ photos:{ $elemMatch:{isPrivate: false} } }).pretty()
我也尝试过:
db.collection_name.find({'photos.isPrivate': true}).pretty()
但是两者都返回数组中的所有元素,即使设置为:
isPrivate: true
请提出建议。
聚合是解决方案。
您需要photos
使用$unwind
运算符解构数组。接下来,使用$match
选择文档isPrivate: false
。该$group
您可以通过重新组合您的文件_id
和重建您photos
使用数组$push
运算符
db.collection_name.aggregate(
[
{$unwind: "$photos"},
{$match: {"photos.isPrivate": false}},
{$group: {"_id": {"id": "$_id", "user": "$user"}, photos: {$push: "$photos"}}}
{$project: {"_id": "$_id.id", "user": "$_id.user", "photos": 1, "_id": 0 }}
]
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句