Yogesh Sajanikar
Yogesh Sajanikar

Reputation: 1116

MongoDB : limit query to a field and array projection

I have a collection that contains following information

{
  "_id" : 1, 
  "info" : { "createdby" : "xyz" }, 
  "states" : [ 11, 10, 9, 3, 2, 1 ]}
}

I project only states by using query

db.jobs.find({},{states:1})

Then I get only states (and whole array of state values) ! or I can select only one state in that array by

db.jobs.find({},{states : {$slice : 1} })

And then I get only one state value, but along with all other fields in the document as well.

Is there a way to select only "states" field, and at the same time slice only one element of the array. Of course, I can exclude fields but I would like to have a solution in which I can specify both conditions.

Upvotes: 2

Views: 1654

Answers (1)

Neo-coder
Neo-coder

Reputation: 7840

You can do this in two ways:

1> Using mongo projection like

<field>: <1 or true> Specify the inclusion of a field

and

<field>: <0 or false> Specify the suppression of the field

so your query as

db.jobs.find({},{states : {$slice : 1} ,"info":0,"_id":0})

2> Other way using mongo aggregation as

db.jobs.aggregate({
    "$unwind": "$states"
  }, {
    "$match": {
      "states": 11
    }
  }, // match states (optional)
  {
    "$group": {
      "_id": "$_id",
      "states": {
        "$first": "$states"
      }
    }
  }, {
    "$project": {
      "_id": 0,
      "states": 1
    }
  })

Upvotes: 1

Related Questions