0

Please find below document structure of mongo Db

{ _id : 0,
   name : "Employee1",
   distributionList :[ { dlname : "ALLEmployee"}, {dlname:"financeall"} ],
   csrActivity : [ {activityname : "blooddonation"}, {activityname : "tree plantation"} ]

}

I want list of employee belonging to financeall distribution list and opted to volunteer tree plantation CSR activity.

Expected resultset as below

{ _id : 0,
   name : "Employee1",
   distributionList :[{dlname:"financeall"} ],
   csrActivity : [  {activityname : "tree plantation"} ]
}

But so far able to achieve below output from query

Query :

db.employee.find(
{name : "Employee1"},
{distributionList : {$eleMatch : {dlname : "financeall"}}}
)

Output :

{ _id : 0,
   name : "Employee1",
   distributionList :[{dlname:"financeall"} ]
}

Using $elemMatch to get the desired output but unable to find how to use it on multiple array within same document. Also tried certain combination but unable to get desired result.

Below query tried but not getting desired output

db.employee.find(
   {name : "Employee1"},
   {distributionList : {$eleMatch : {dlname : "financeall"}}},
   {csrActivity: {$eleMatch : {activityname : "tree plantation"}}}
)

Any help will be highly appreciated

4
  • 1
    Try db.employee.find( {name : "Employee1"}, {distributionList : {$elemMatch : {dlname : "financeall"}}, csrActivity: {$elemMatch : {activityname : "tree plantation"}}} ) Commented Sep 11, 2018 at 7:17
  • Already tried this query and also updated that in my question it does not work Commented Sep 11, 2018 at 7:19
  • Please take a look at the query carefully. It's not the same. Commented Sep 11, 2018 at 7:20
  • Yeah its working thanks appreciate your help Commented Sep 11, 2018 at 7:26

1 Answer 1

1

You only misspelled the projection operator $elemMatch

The correct query is:

db.employee.find(
  {
    name: "Employee1"
  }, {
    distributionList: {
        $elemMatch: {
            dlname: "financeall"
        }
    },
    csrActivity: {
        $elemMatch: {
            activityname: "tree plantation"
        }
    }
  }
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.