MongoDB-搜索子文档

MongoDB-搜索子文档,mongodb,mongodb-query,Mongodb,Mongodb Query,我正在尝试在子文档中搜索。这是我的文档结构: { _id: <ObjectID>, email: ‘test@emample.com’, password: ‘12345’, images: [ { title: ‘Broken Hand’, description: ‘Here is a full description’, comments: [

我正在尝试在子文档中搜索。这是我的文档结构:

{
    _id: <ObjectID>,
    email: ‘test@emample.com’,
    password: ‘12345’,
    images: [
        {
            title: ‘Broken Hand’,
            description: ‘Here is a full description’,
            comments: [
                {
                    comment: ‘Looks painful’,
                }
            ],
            tags: [‘hand’, ‘broken’]
         }  
    ]
}
有人能告诉我如何获得所有图像的正确方向吗?

您可以使用:

db.site_users.aggregate([
    {$unwind: "$images"},
    {$match:{
        "images.tags": "broken"
    }}
])

查询很好,因为它与文档匹配,但“投影”超出了您可以使用
.find()
执行的范围,您需要
.aggregate()
并注意不要从数组中删除“图像”项,而只删除不匹配的“标记”

理想情况下,您可以在MongoDB 3.2中使用inside:

db.site\u users.aggregate([
{“$match”:{“images.tags”:“breaked”},
{“$project”:{
“电子邮件”:1,
“密码”:1,
“图像”:{
“$filter”:{
“输入”:“$images”,
“as”:“image”,
“条件”:{
“$setIsSubSet”:[[“断开”],“$$image.tags”]
}
}
}
}}
])
或者可能使用并且也与MongoDB 2.6兼容,只要每个条目的“图像”内容是“唯一的”。这是由于“设置”操作,其中“设置”是“唯一的”:

db.site\u users.aggregate([
{“$match”:{“images.tags”:“breaked”},
{“$project”:{
“电子邮件”:1,
“密码”:1,
“图像”:{
“$setDifference”:[
{“$map”:{
“输入”:“$images”,
“as”:“image”,
“在”:{
“$cond”:{
“if”:{“$setIsSubSet”:[[“断开”],“$$image.tags”]},
“然后”:“$$image”,
“else”:false
}
}
}},
[错误]
]
}
}}
])
这可以在早期版本的MongoDB中完成,但由于在阵列上处理的成本,最好避免:

db.site\u users.aggregate([
{“$match”:{“images.tags”:“breaked”},
{“$unwind”:“$images”},
{“$match”:{“images.tags”:“breaked”},
{“$组”:{
“\u id”:“$\u id”,
“电子邮件”:{“$first”:“$email”},
“密码”:{“$first”:“$password”},
“图像”:{“$push”:“$images”}
}}       
])
由于在不“聚合”任何内容的情况下使用此方法通常会产生相当大的成本,因此,如果没有其他实用方法可用的现代版本,通常最好在客户端代码中而不是在服务器上“过滤”数组内容本身

因此,在这种情况下,您应该只使用数组项按移除不匹配项的顺序“显著”减少的方法。否则,处理成本可能大于传输数据的网络成本,任何好处都将被抵消


如果你没有现代版,那就买一个吧。这些特性使实用性和性能完全不同。

您的元素匹配似乎在项目部分而不是筛选部分(但我可能弄错了)。请尝试:
db.site\u users.find({'images.tags':“breaked”,{images:{$elemMatch:{'tags':'breaked'}}}},{images:1})。pretty()
db.site_users.aggregate([
    {$unwind: "$images"},
    {$match:{
        "images.tags": "broken"
    }}
])