1

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
            }
    ]
    }
kaye_g
  • 13
  • 5

1 Answers1

1

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.

J.F.
  • 13,927
  • 9
  • 27
  • 65
  • Is it also possible to get that with an id not matching its own id? I would like to check if there is any duplicated accountGroupName in the whole collection. – kaye_g Jun 25 '21 at 02:16