运算符$ arrayElemAt与Mongo <3.2聚合

ack*_*ser 5 javascript mongodb mongodb-query aggregation-framework

使用Mongo中的聚合框架,

如何在Mongo <3.2 中使用操作$ arrayElemAtMongo 3.2中获得相同的结果?

Mongo 3.2中的示例

采集

{ "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }
Run Code Online (Sandbox Code Playgroud)

询问

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

它工作正常

但是,我被迫使用Mongo 3.0,所以我不能使用这个操作符,这对我想做的事情来说是理想的

有没有办法通过索引访问数组元素...

Mongo 3.0

采集

{ "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }
Run Code Online (Sandbox Code Playgroud)

询问

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

我尝试过它不起作用,它给了我一个空数组.

但是,当它们是属性而不是索引时,它能够检索值

任何帮助将非常感激.

谢谢

sty*_*ane 7

你将需要$unwind,$group并使用像这样的$first$last运算符:

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

或两个不同的查询,如果$unwind是昂贵的

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