MongoDb 使用某些 属性 访问对象数组

MongoDb Access array of objects with certain property

我有一份文件如下:

{
    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()

但是 return 数组中的所有元素甚至设置为 :

的元素
isPrivate: true

求推荐。

Aggregation 是解决方案。

您需要使用 $unwind operator. Next use the $match to select documents where isPrivate: false. The $group you can regroup your documents by _id and reconstruct your photos array using the $push 运算符

解构 photos 数组
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 }}
     ]
)

您可以像这样对结果投影使用 $elemMatch

db.collection_name.find(
{ photos:{ $elemMatch:{isPrivate: false} } },   //1

{photos:{$elemMatch:{isPrivate: false}}})  //2
  1. 查找至少有一张非私人照片的所有文档
  2. Select 只有找到的文档的非私密照片。