[英]How to find a value of a specified object property in a array using mongoose find()
My schema我的架构
{
_id: xxxxxxxxxxxxx,
totalCreatedForms: [
{formName: "formone", formIndex: 0},
{formName: "formtwo", formIndex: 1},
{formName: "formthree", formIndex: 2}
]
}
I used mongoose query to find the form I need as follows:我使用 mongoose 查询来查找我需要的表单,如下所示:
db.collection.find({"totalCreatedForms.formName":"formtwo"}, data=>{res.send(data)})
Is there a way, I can get the value of formIndex of the specified form.有没有办法,我可以得到指定表单的formIndex的值。 Here I am getting the whole data of the "_id", I have to filter again it in the front-end.
这里我得到了“_id”的全部数据,我必须在前端再次过滤它。 But, I am wondering if there is a query to get the values of the specified form.
但是,我想知道是否有查询来获取指定表单的值。
You need $
operator in this way:您需要以这种方式
$
运算符:
db.collection.find({
"totalCreatedForms.formName": "formtwo"
},
{
"_id": 0,
"totalCreatedForms.formIndex.$": 1
})
Find query has two objects.查找查询有两个对象。
The first to match the element you are looking for.第一个匹配您要查找的元素。
The second one is to indicate which fields returns.第二个是指示哪些字段返回。 So,
_id
field will not be returned and, from array, only the index where the positional operator is placed, will be returned.因此,不会返回
_id
字段,并且从数组中,只会返回放置位置运算符的索引。
Ouput example is like this:输出示例是这样的:
[
{
"totalCreatedForms": [
{
"formIndex": 1
}
]
}
]
Note that mongo is a data base who store documents and return documents, so this is the easiest way (without aggregation) to get only the value you want instead of the entire array.请注意,mongo 是一个存储文档并返回文档的数据库,因此这是仅获取所需值而不是整个数组的最简单方法(无需聚合)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.