如果我理解正确的话,这在 mongodb 中称为投影
。我发现有两种有用的投影运算符:elemMatch
和 $
。
我有一组文档,每个文档都有一个属性列表(对象)。我想执行复杂的查询来匹配这些属性,即匹配其多个字段(使用regex
等)。
现在,当文档与查询匹配时,Java 驱动程序将返回整个文档。我想过滤它以仅返回与原始查询匹配的属性。
我尝试过组合elemMatch
,但我所能完成的只是返回所有属性或仅返回一个属性(通常是第一个匹配项)。
Mongo文档结构如下:
{
"name": "MediaPlayer",
"attributes": [
{
"tag": "media",
"values": [
"mp3",
"mp4"
]
},
{
"tag": "teste",
"values": [
"teste"
]
}
]
}
我的查询为:
{attributes : {$elemMatch: { 'tag' : 'media'},$elemMatch: { 'tag' : 'stream'}}}
它返回以下结果:
{
"name": "MediaStream",
"attributes": [
{
"tag": "media",
"values": [
"Edit"
]
},
{
"tag": "stream",
"values": [
"Edit"
]
},
{
"tag": "video",
"values": [
"Edit"
]
}
]
}
示例和返回是不同的文档。尽管我匹配了两个属性,但我返回了整个列表。
我希望属性数组仅包含匹配的元素。
我怎样才能做到这一点?
编辑:
据我所知,mongodb find 操作不支持内部数组过滤。有一些使用 mongodb 聚合框架的示例。除此之外,手动进行过滤似乎是唯一可能的方法。
最佳答案
假设您想要匹配 tag:media
和 tag:stream
,这种情况下您在 mongo $in 中输入了匹配条件聚合查询如下
db.collectionName.aggregate({
"$unwind": "$attributes" // first unwind attributes array
}, {
"$match": {
"attributes.tag": {
"$in": ["media", "stream"] // put all matching tags in array using $in
}
}
}, {
"$group": {
"_id": "$_id",
"name": {
"$first": "$name"
},
"attributes": {
"$push": "$attributes" // push all attributes to get only matching tags
}
}
}).pretty()
关于java - 过滤 mongodb 查询后返回的数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29822976/