Operator $arrayElemAt in aggregation with Mongo < 3.2

浪子不回头ぞ 提交于 2019-12-19 07:39:31

问题


Using the aggregation framework in Mongo,

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

Example in Mongo 3.2

Collection

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

Query

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

It works fine

But, I have been forced to used Mongo 3.0 so I can't use this operator, which is ideal for what I want to do

Is there any way to accessing an element of an array by index with something like...

Mongo 3.0

Collection

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

Query

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

I tried and it doesn't work, it gives me an empty array.

However, when they are properties rather than indexes it is able to retrieve the values

Any help would be really appreciated.

Thanks


回答1:


You will need to $unwind, $group and use the $first and $last operators like this:

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

Or two different queries if $unwind is expensive

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


来源:https://stackoverflow.com/questions/41057372/operator-arrayelemat-in-aggregation-with-mongo-3-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!