How do I use the document field value as an argument to $ slice?

Consider these two documents:

{ currentIndex: 1, elements: [4, 5, 6] }
{ currentIndex: 2, elements: [4, 5, 6] }

      

How do I get this result sorted by the item elements

in the index currentIndex

?

{ currentIndex: 1, elements: [5] }
{ currentIndex: 2, elements: [6] }

      

I read about $ slice [1], but it seems that the arguments for it cannot be dynamic. All examples use actual integers as arguments for it, rather than a string that identifies a value in the document to use as an index.

[1] http://docs.mongodb.org/manual/reference/operator/projection/slice/

+3


source to share


2 answers


If currentIndex is unique, or you can add a unique field to your collection, you can use mapreduce:



db.coll.mapReduce(
    function() {
        emit(this.currentIndex, { currentIndex: this.currentIndex, elementAtCurrentIndex: this.elements[this.currentIndex]});
    }, function(key, values) {
        return values[0];
    }, {
        out: "result"
    }
)

db.result.find({}, {"value.currentIndex":1, "value.elementAtCurrentIndex":1, _id:0}).sort({"value.elementAtCurrentIndex":1})

      

+1


source


For relatively small datasets, you can use the cursor method to iterate over the cursor and access documents, use native JavaScript splice to get the array you want and store the results in another collection, as in the following example: forEach()

db.collection.find().forEach(function (doc){
    doc.elements = doc.elements.splice(doc.currentIndex, 1);
    db.result.save(doc);
})

      

Check out the demo below



var cur = [
    { currentIndex: 1, elements: [4, 5, 6] },
    { currentIndex: 2, elements: [4, 5, 6] }
];
var results = [];
cur.forEach(function (doc){
    doc.elements = doc.elements.splice(doc.currentIndex, 1);        
    results.push(doc);
});

pre.innerHTML = JSON.stringify(results);
      

<pre id="pre"></pre>
      

Run codeHide result


0


source







All Articles