MongoDB query to display alternative documents with mapReduce() function and emit even field values

To display alternative documents with the mapReduce() function and emit even field values in MongoDB, use a custom counter in the scope parameter to track document order and emit only documents at even positions.

Syntax

db.collection.mapReduce(
    function() {
        counter++;
        var id = this._id;
        delete this._id;
        if (counter % divisor != 0)
            emit(id, this);
    },
    function() {},
    {
        "scope": { "counter": 0, "divisor": 2 },
        "out": { "inline": 1 }
    }
)

Sample Data

db.demo636.insertMany([
    {id: 1},
    {id: 2},
    {id: 3},
    {id: 4},
    {id: 5},
    {id: 6}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e9c127b6c954c74be91e6d2"),
        ObjectId("5e9c127e6c954c74be91e6d3"),
        ObjectId("5e9c127f6c954c74be91e6d4"),
        ObjectId("5e9c12816c954c74be91e6d5"),
        ObjectId("5e9c12836c954c74be91e6d6"),
        ObjectId("5e9c12896c954c74be91e6d7")
    ]
}

Example: Display Alternative Documents

db.demo636.mapReduce(
    function () {
        oddCounter++;
        var id = this._id;
        delete this._id;
        if (oddCounter % d != 0)
            emit(id, this);
    },
    function() {},
    {
        "scope": { "oddCounter": 0, "d": 2 },
        "out": { "inline": 1 }
    }
)
{
    "results": [
        {
            "_id": ObjectId("5e9c127b6c954c74be91e6d2"),
            "value": {
                "id": 1
            }
        },
        {
            "_id": ObjectId("5e9c127f6c954c74be91e6d4"),
            "value": {
                "id": 3
            }
        },
        {
            "_id": ObjectId("5e9c12836c954c74be91e6d6"),
            "value": {
                "id": 5
            }
        }
    ],
    "timeMillis": 29,
    "counts": {
        "input": 6,
        "emit": 3,
        "reduce": 0,
        "output": 3
    },
    "ok": 1
}

How It Works

  • Map function: Increments a counter for each document and emits only documents where counter % 2 != 0 (odd positions)
  • Scope parameter: Initializes the oddCounter variable and divisor d
  • Result: Returns documents at positions 1, 3, and 5 (alternative documents)

Conclusion

The mapReduce() function with a custom counter in the scope allows filtering alternative documents. The map function tracks document order and emits only documents at specified positions based on the modulo operation.

Updated on: 2026-03-15T03:13:55+05:30

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements