kaye_g
kaye_g

Reputation: 13

Mongoose getting specific item in Embedded Document

I am new in NoSQL and I'm kinda stuck. Can you help me?

Is there any way to get the specific field in an array if it matches a value? For example, I would like to get the specific item in the array accountGroup where accountGroupName=="Account 1".

I tried many codes but it just returns the whole array which has the item that matches with the value.

By the way, I am using Mongoose and Nodejs. Thanks.

   //here is the database    
   {
    "_id" : ObjectId("60d2db4b90c66c3b0832a616"),
    "accountType" : "Account Type 1",
    "accountGroup" : [
            {
                    "_id" : ObjectId("60d2db5a90c66c3b0832a619"),
                    "accountGroupName" : "Account 1",
                    "rangeFrom" : 25,
                    "rangeTo" : 35
            },
            {
                    "_id" : ObjectId("60d3fbfbc1502c3ed8cadf86"),
                    "accountGroupName" : "Account2",
                    "rangeFrom" : 850,
                    "rangeTo" : 2000
            },
            {
                    "_id" : ObjectId("60d2ddb1396dbf384898fbad"),
                    "accountGroupName" : "account 1 sample 3",
                    "rangeFrom" : 10,
                    "rangeTo" : 15
            }
    ],
    }
    {
    "_id" : ObjectId("60d2db4e90c66c3b0832a617"),
    "accountType" : "Account Type 2",
    "accountGroup" : [
            {
                    "_id" : ObjectId("60d2e9586c4fa82310349c7c"),
                    "accountGroupName" : "account 2 sample 5",
                    "rangeFrom" : 50,
                    "rangeTo" : 60
            }
    ]
    }

Upvotes: 1

Views: 531

Answers (1)

J.F.
J.F.

Reputation: 15177

You can use position operator $ into projection like this:

YourModel.find({
  "accountGroup.accountGroupName": "Account 1"
},
{
  "accountGroup.$": 1
})

Example here

Note that you are getting the whole document because using

YourModel.find({"accountGroup.accountGroupName": "Account 1"})

You are telling mongo "Give me a document where value accountGroupName into accountGroup array is equal to Account 1. And the document who match that condition contains the whole array.

So using positional operator, is waht you need according to its description:

The positional $ operator limits the contents of an to return the first element that matches the query condition on the array.

This is why with one query you get the whole document and with the other one you get the value you want.

Also note $ return only the first subdocument that match the query.

Upvotes: 1

Related Questions