The $ arrayElemAt statement in aggregation with Mongo <3.2

Using the aggregation structure in Mongo,

How can I achieve the same result in Mongo <3.2 , as in Mongo 3.2 with the $ arrayElemAt operation ?

Example in Mongo 3.2

Collection

{ "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }

Inquiry

db.users.aggregate([
   {
     $project:
      {
         name: 1,
         first: { $arrayElemAt: [ "$favorites", 0 ] },
         last: { $arrayElemAt: [ "$favorites", -1 ] }
      }
   }
])

It works great

But I was forced to use Mongo 3.0, so I can’t use this operator, which is perfect for what I want to do

Is there a way to access an array element by index with something like ...

Mongo 3.0

Collection

{ "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }

Inquiry

db.users.aggregate([
   {
     $project:
      {
         name: 1,
         first: { "$favorites.0" },
         last:  { "$favorites.1" }
      }
   }
])

I tried and it does not work, it gives me an empty array.

However, when they are properties, not indexes, it can retrieve values

Any help would be really appreciated.

thank

+4
1

$unwind, $group $first $last :

db.collection.aggregate([
    { "$unwind": "$favorites" },
    { "$group": { 
        "_id": "$_id",
        "first": { "$first": "$favorites" },
        "last": { "$last": "$favorites" }
    }}
])

, $unwind

var first = db.collection.find({}, {"favorites": { $slice: 1}})
var last = db.collection.find({}, {"favorites": { $slice: -1}})
+5

Source: https://habr.com/ru/post/1663308/


All Articles