Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

Aggregate Element ที่ 2 จาก Input Element ใน MongoDB

การ Aggregate Element ที่ 2 ด้วย mapReduce()

เพื่อ Aggregate Element ที่ 2 จาก Input Element ให้ใช้ mapReduce() Map-reduce เป็น Paradigm การประมวลผลข้อมูลสำหรับ凝縮ข้อมูลปริมาณมากให้เป็นผลลัพธ์ที่มีประโยชน์

สร้าง Collection พร้อมข้อมูล

> db.demo621.insert({ _id: 101, Name1: "John", Name2: "John" });
WriteResult({ "nInserted" : 1 })
> db.demo621.insert({ _id: 102, Name1: "Bob", Name2: "John" });
WriteResult({ "nInserted" : 1 })
> db.demo621.insert({ _id: 103, Name1: "Chris", Name2: "John" });
WriteResult({ "nInserted" : 1 })
> db.demo621.insert({ _id: 104, Name1: "Sam", Name2: "John" });
WriteResult({ "nInserted" : 1 })

แสดงเอกสารทั้งหมด

> 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" }

คิวรี Aggregate Element ที่ 2

> 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
}