5

a doc {"m":[1,2,3], "others":xxx}, get the first element in array 'm' by:

db.find({query},{"m":{$slice:1}, "m":1})

the return is {"m":[1]}, the element in doc is an array. But in this query, only one element in array will be get, so I don't need the return doc contain array which has only one element. This is like SQL local variable in sub-query. The element I want has no name in original doc, if I want get it then I need to make a name for it, the doc returned I wanted is like: {"localVariable":1} rather than {"m":[1]}

I try to project out the first element by:

db.find({query},{"m":{$slice:1}, "m.1":1})

but this don't work.

3
  • 1
    What is the question mark for? Commented Mar 14, 2014 at 3:32
  • @jean I am guessing at your meaning. Do you want: "The first element of the array, but not as an array value, and just return the value? You cannot do that. Not with find. Maybe with aggregate but I still doubt this is what you want really. Just learn to use the array return value. It's an array with one element. That should not be hard. The way you have presented this question is clearly not your real coding use case. You would do better to ask a question that is about the real code and problem you need to solve. Commented Mar 15, 2014 at 5:00
  • From js api it indeed hard to distinguish the difference. I am using c++ driver, in this situation, the code writing is very boring. Every time I need get the m doc and convert it to a container of doc, and get the first element then convert it to int value. Commented Mar 15, 2014 at 6:05

1 Answer 1

1

You seem to be looking for a positional $ operator match. It works like this:

 db.collection.find({ m: 2 },{ "m.$": 1 })

That will return you the matched element

If you are in fact looking to always get the second element, then you need the two argument form of $slice:

 db.collection.find({ },{ "m": { "$slice": [1,1] } })

Tested output:

 db.test.insert({ m: [1,2,3] })
 db.test.find({ },{ "m": {$slice: [1,1]} })

  { "_id" : ObjectId("5323cc2770fde63cf1146ba3"), "m" : [  2 ] }
Sign up to request clarification or add additional context in comments.

3 Comments

the return still be {"m":[1]}
@jean No it does not. See the output from what I have run added to the answer
I revised my question. I want it return {"othername":1} rather than {"m":[1]}. I want project out the element which in array

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.