[英]How to find matching elements from an array of objects using mongoDB query
I want to find all elements matching product "bat".我想找到所有匹配产品“bat”的元素。 My structure for database is as follows
我的数据库结构如下
[
{
"key": 1,
"productArray" : [
{
"requirementId": 5,
"product": "bat"
},
{
"requirementId": 6,
"product": "Pen"
},
]
},
{
"key": 2
},
{
"key": 3,
"productArray": [
{
"requirementId": 1,
"product": "bat"
},
{
"requirementId": 2,
"product": "Pen"
},
{
"requirementId": 3,
"product": "bat"
},
{
"requirementId": 4,
"product": "bat"
}
]
}
]
I have tried the following query but this query is returning only one matching element.我尝试了以下查询,但此查询仅返回一个匹配元素。
db.collection.find({"key": 3}, {"productArray": {"$elemMatch": { "product": "bat"}}})
result of above query is as follows上述查询结果如下
[
{
"_id": ObjectId("5a934e000102030405000002"),
"productArray": [
{
"product": "bat",
"requirementId": 1
}
]
}
]
Can I get expected output for my problem is as follows using mongodb query Or should I use another approach for my case:我可以得到预期的 output 我的问题如下使用 mongodb 查询或者我应该使用另一种方法来处理我的情况:
My expected output is as follows我预期的output如下
[
{
"productArray": [
{
"requirementId": 1,
"product": "bat"
},
{
"requirementId": 3,
"product": "bat"
},
{
"requirementId": 4,
"product": "bat"
}
]
}
]
As you found, $elemMatch
but also $
are lazy operators and return the first element that matches.如您所见,
$elemMatch
和$
都是惰性运算符,并返回匹配的第一个元素。
You could add a pipeline in find (mongoDB 4.4+) but aggregation is better supported:您可以在 find (mongoDB 4.4+) 中添加管道,但更好地支持聚合:
db.collection.aggregate({
$match: {
key: 3
}
},
{
$project: {
productArray: {
"$filter": {
"input": "$productArray",
"as": "p",
"cond": {
$eq: [
"$$p.product",
"bat"
]
}
}
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.