-1

how can I get an object of array by index

example:

{ "_id" : 1, "name" : "bob", colors: [ "red", "blue", "green"] }
{ "_id" : 2, "name" : "jim", colors: ["yellow", "black" ] }

my query: something like

db.users.find({name: "bob"}, {colors: 2})

result:

{ "_id" : 1, "name" : "bob", colors: "blue" }
0

2 Answers 2

1

You can try below aggregation

db.collection.aggregate([
  { "$match": { "name": "bob" }},
  { "$project": {
    "name": 1,
    "color": { "$slice": [ "$colors", 1, 1 ] }
  }},
  { "$unwind": "$color" }
])

Above query will return

[
  {
    "_id": 1,
    "color": "blue",
    "name": "bob"
  }
]
Sign up to request clarification or add additional context in comments.

Comments

0

You can use $arrayElemAt to get the n-th item in array:

db.users.aggregate([
      {$match: {name: "bob"}},
      {$project: {name: "$name", color: {$arrayElemAt: ['$colors', 1]}}}
])

Note that the index is 0-based.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.