-2

This is my document in MongoDB and I need to limit the output:

{
    "_id": ObjectId("55880fb8c3addd201ee2f70e"),
    "title": "Sales",
    "level1": [{
    "name": "Master",
    "link": "/sales/master"
    }, {
    "name": "eCommerce",
    "link": "/sales/ecommerce"
    }]
}

My search query is:

db.collection.find({
    title: "Sales",
    "level1.name": "Master"
}, {
    "title": 1,
    "level1.name": 1,
    "level1.name": "Master"
})

This is the expected output:

{
    "_id": ObjectId("55880fb8c3addd201ee2f70e"),
    "title": "Sales",
    "level1": [{
    "name": "Master",
    "link": "/sales/master"
    }]
}
Vishwas
  • 6,967
  • 5
  • 42
  • 69
Alnoor Khan
  • 53
  • 1
  • 10

2 Answers2

0

Please try the below query :

 db.collection.find({title :"Sales",
                     level1: {$elematch: {name" : "Master"}}},
                    {title : 1, level1.$ : 1});
Yathish Manjunath
  • 1,919
  • 1
  • 13
  • 23
  • db.collection.find({"title":"Sales","level1":{"$elemMatch":{"name":{$in :["Master","eCommerce"]}}}},{"level1.$name":1,"title":1})...How to search for n no.of $elematch – Alnoor Khan Jul 08 '15 at 11:27
  • @AlnoorKhan The question has been asked many times before. Look at the linked duplicate answer at is has **all** your answers. – Blakes Seven Jul 08 '15 at 11:34
0

You can use aggregation by $unwind level1 array to get expected result like following:

db.collection.aggregate({$unwind:"$level1"},{$match:{"level1.name":"Master","title" :"Sales"}})

If you want all under one array you can group it like :

db.collection.aggregate({$unwind:"$level1"},{$match:{"title" :"Sales","level1.name":"Master"}},{$group:{_id:"_id","title":{$first:"$title"},"level1":{$push:"$level1"}}})
Vishwas
  • 6,967
  • 5
  • 42
  • 69