[英]mongodb How to find only part of an array
I want to get an array returned using the "find" function in the data below The contents of the array are as follows.我想在下面的数据中得到一个使用“find”函数返回的数组,该数组的内容如下。
{qty:15 warehouse:C},
{qty:20 warehouse:C},
{qty:25 warehouse:C}
I don't want "first element"我不想要“第一个元素”
I want to return an array where gty is greater than 20.我想返回一个 gty 大于 20 的数组。
How can I do this?我怎样才能做到这一点?
Receive document returned from mongodb接收mongodb返回的文档
Do I have to pull it out directly with a loop?我必须直接用一个环把它拉出来吗?
Is there a way to get it out with a query?有没有办法通过查询来解决它?
{
_id: ObjectId('60d0b364737d829c870b7571'),
item: 'journal',
instock: [
{
warehouse: 'A',
qty: 5
},
{
warehouse: 'C',
qty: 15
},
{
warehouse: 'C',
qty: 20
},
{
warehouse: 'C',
qty: 25
}
]
}
You can use Aggregation Pipeline:您可以使用聚合管道:
$match
to match all documents that you want to query $match
匹配您要查询的所有文档$project
to select what fields you want to return $project
选择要返回的字段$filter
to filter instock
array by some condition $filter
按某种条件过滤instock
数组db.collection.aggregate([
{
"$match": {
"_id": "id_1"
}
},
{
"$project": {
"item": 1,
"instock": {
"$filter": {
"input": "$instock",
"cond": {
"$gt": [
"$$this.qty",
20
]
}
}
}
}
}
])
Here is a working example: https://mongoplayground.net/p/-RPGEriBxui这是一个工作示例: https : //mongoplayground.net/p/-RPGEriBxui
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.