0
db.sample.find():
 {_id:1, locations: [{vname: "edd", distr: "prakasam"}, {vname: "vij", distr: "krishna"}, {vname: "kakani", distr: "guntur"}]};

I want to find the locations other than vname: "vij"

My result could be

{_id: 1, locations: [{vname: "edd", distr: "prakasam"}, {vname: "kakani", distr: "guntur"}]};

I tried with the following queries but couldn't helped me out.

db.sample.find({'locations.$.vname': {$ne: 'vij'}})

It is returning entire document but I need to exclude this document.

Any Help is appreciable.

Sandeep sandy
  • 387
  • 7
  • 14

3 Answers3

2

Use $redact. $$PRUNE when locations array matches vname as vij

db.sample.aggregate({
    $redact: {
        $cond: [{
                $eq: ["$vname", "vij"]
            },
            "$$PRUNE",
            "$$DESCEND"
        ]
    }
});
s7vr
  • 73,656
  • 11
  • 106
  • 127
0

Try this:

> db.sample.find({"locations.vname": {$ne: "vij"}})
Natalja Olefire
  • 442
  • 5
  • 9
0

As the location is an array of objects in your schema, you can't exclude a particular object from the result. You can exclude the whole location field from the result. However, you have an option to run aggregation on your collection.

db.sample.aggregate([
     {
        "$match" :{"_id":1}
     }, 
     {
        "$unwind" :"$locations"
     },
     {
        "$match" :{
           "locations.vname":{"$ne": "vij"}
         }
     }
    ])

This will return data in this form.

{ "_id" : 1, "locations" : { "vname" : "edd", "distr" : "prakasam" } }
{ "_id" : 1, "locations" : { "vname" : "kakani", "distr" : "guntur" } }
Tarush Arora
  • 576
  • 3
  • 10
  • This is fine, But I need the output as mentioned in the post. That too "locations" field type is getting changed rather than array it is becoming an object/document. Could you help to get in that format. Thankyou. – Sandeep sandy Jan 31 '17 at 19:57