2

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.

4
  • 1
    aggregation is your friend. $unwind states; use $match to filter and $project to reshape or exclude fields Commented May 26, 2015 at 14:36
  • can you post your expected output ? Commented May 26, 2015 at 15:48
  • @yogesh The expected output should contain only "states" with only one array value. Commented May 27, 2015 at 4:51
  • So for simple field selection, the field selection works alright. Will it be a good idea to allow these simple limiting expressions inside find projections. Commented May 27, 2015 at 5:19

1 Answer 1

1

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
    }
  })
Sign up to request clarification or add additional context in comments.

1 Comment

I used aggreation to include [ { $project : "states" }, { $unwind : "states" }, { $limit : 1} ]

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.