Get a specific item in a Mongo DB $ group

I am testing Mongo 2.6 and zips sample data and I would like to be able to get either latitude or longitude during the request and use a common structure, here is an example that I combined:

db.zips.aggregate([{
  $project: {
    _id: 1,
    city: 1,
    loc: 1
  }
}, {
  $unwind: '$loc'
}, {
  $group: {
    "_id": "$_id",
    "city": {
      $first: "$city"
    },
    "lat": {
      $first: "$loc"
    }
  }
}])

$slice does exactly what I want, instead of $ unwind and $ group, because I just want to extract a specific field from the array, but you cannot use it in the aggregation structure from what I can say.

So $unwindit seems to work the same way when I group, the problem $firstis great when collecting the first element, and technically I could use it as a block of 2 elements $last, but if it were> 2 elements, as I would say I want an element 2nd?

=== Editing ===

https://jira.mongodb.org/browse/SERVER-4589

, , , , , . , .

+4
1

, , , . MapReduce. .

, , , :

db.runCommand({
  "mapreduce" : "zips",
  "map" : function() {
    emit(this._id, {
      city: this.city, 
      lat: this.loc[0], // First array elem
      long: this.loc[1] // Second array elem
    });
  },
  "reduce" : function(key, values) { return values[0]; }, 
  "out": { inline: 1 }
});

, . , .

0

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


All Articles