Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB Aggregate Second Element from Input Element?
To aggregate second element from input element in MongoDB, use mapReduce() with a counter variable in the scope. This method allows you to skip elements and select specific positions from a collection based on a divisor pattern.
Syntax
db.collection.mapReduce(
function() {
track++;
if (track % div == 0) {
emit(key, value);
}
},
function() {},
{
"scope": { "track": 0, "div": 2 },
"out": { "inline": 1 }
}
);
Sample Data
db.demo621.insertMany([
{ _id: 101, Name1: "John", Name2: "John" },
{ _id: 102, Name1: "Bob", Name2: "John" },
{ _id: 103, Name1: "Chris", Name2: "John" },
{ _id: 104, Name1: "Sam", Name2: "John" }
]);
{ "acknowledged": true, "insertedCount": 4 }
Display All Documents
db.demo621.find();
{ "_id": 101, "Name1": "John", "Name2": "John" }
{ "_id": 102, "Name1": "Bob", "Name2": "John" }
{ "_id": 103, "Name1": "Chris", "Name2": "John" }
{ "_id": 104, "Name1": "Sam", "Name2": "John" }
Example: Aggregate Every Second Element
db.demo621.mapReduce(
function() {
track++;
var actualId = this._id;
delete this._id;
if (track % div == 0)
emit(actualId, this);
},
function() {},
{
"scope": { "track": 0, "div": 2 },
"out": { "inline": 1 }
}
);
{
"results": [
{
"_id": 102,
"value": {
"Name1": "Bob",
"Name2": "John"
}
},
{
"_id": 104,
"value": {
"Name1": "Sam",
"Name2": "John"
}
}
],
"timeMillis": 48,
"counts": {
"input": 4,
"emit": 2,
"reduce": 0,
"output": 2
},
"ok": 1
}
How It Works
- The track variable increments for each document processed
- When
track % div == 0(every 2nd element), the document is emitted - The scope parameter defines global variables accessible in map function
- Setting
div: 2selects every second element (positions 2, 4, 6, etc.)
Conclusion
MapReduce with scope variables provides a way to select elements at specific intervals from MongoDB collections. By using a counter and modulo operation, you can efficiently extract every nth element from your dataset.
Advertisements
