-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" }
dina
  • 4,039
  • 6
  • 39
  • 67

2 Answers2

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"
  }
]
Ashh
  • 44,693
  • 14
  • 105
  • 132
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.

Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51