简体   繁体   中英

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:

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. Here I am getting the whole data of the "_id", I have to filter again it in the front-end. 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.

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.

Example here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM