具有对象数组的Mongo DB聚合 [英] Mongo DB aggregation with array of objects
本文介绍了具有对象数组的Mongo DB聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的收集模式如下:
产品
{
_id: ObjectId(), // default mongo db id
specification: [
{key: 'Name', value: "value 1"},
{key: 'Category', value: "value 2"},
{key: 'Department', value: "value 3"}
]
}
现在,我想使用通用过滤器对此进行查询.例如
Now I want to query on this with a generic filter. For example,
- 让我使用
Name = value 1
和Category in [value 2, value 3]
和Department = value 3
获得所有产品
- 使用
Name = value 1
或Category = value 2
或Department in [value 3, value 4]
给我所有产品
- Get me all product with
Name = value 1
andCategory in [value 2, value 3]
andDepartment = value 3
- Get me all product with
Name = value 1
orCategory = value 2
orDepartment in [value 3, value 4]
我一直在尝试将$match
与$elemMatch
一起使用.但这仅允许一个查询,但是我不能使用$and
和$or
运算符.
I have been trying to use $match
with $elemMatch
. But that only allows only one query but I am not able to use the $and
and $or
operator.
推荐答案
您可以很好地使用$elemMatch
,只需将$and
/$or
放在最顶层即可.
You can use $elemMatch
just fine, you just have to put $and
/ $or
at the top level.
您的第一个示例是
db.products.find({
$and: [
{
specification: {
$elemMatch: { key: 'Name', value: 'value 1' }
}
},
{
specification: {
$elemMatch: { key: 'Category', value: { $in: ['value 1', 'value 2'] } }
}
},
{
specification: {
$elemMatch: { key: 'Department', value: 'value 3' }
}
}
]
})
这篇关于具有对象数组的Mongo DB聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文