使用 mapReduce() 函数并发出偶数字段值的 MongoDB 查询以显示替代文档
让我们创建一个具有文档的集合 -
> db.demo636.insert({id:1});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:2});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:3});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:4});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:5});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:6});
WriteResult({ "nInserted" : 1 })在集合中使用 find() 方法显示所有文档 -
> db.demo636.find();
这将生成以下输出 -
{ "_id" : ObjectId("5e9c127b6c954c74be91e6d2"), "id" : 1 }
{ "_id" : ObjectId("5e9c127e6c954c74be91e6d3"), "id" : 2 }
{ "_id" : ObjectId("5e9c127f6c954c74be91e6d4"), "id" : 3 }
{ "_id" : ObjectId("5e9c12816c954c74be91e6d5"), "id" : 4 }
{ "_id" : ObjectId("5e9c12836c954c74be91e6d6"), "id" : 5 }
{ "_id" : ObjectId("5e9c12896c954c74be91e6d7"), "id" : 6 }以下是实现 mapReduce() 并仅显示偶数的查询 -
> 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
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP