MongoDB查询以使用Map Reduce概念获取随机值。
对于使用Map Reduce的随机值,请使用mapReduce()概念以及Math.random()。让我们创建一个包含文档的集合-
> db.demo651.insertOne({Value:10});{
"acknowledged" : true,
"insertedId" : ObjectId("5e9f0330e3c3cd0dcff36a57")
}
> db.demo651.insertOne({Value:20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9f0332e3c3cd0dcff36a58")
}
> db.demo651.insertOne({Value:30});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9f0335e3c3cd0dcff36a59")
}
> db.demo651.insertOne({Value:40});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9f0337e3c3cd0dcff36a5a")
}
> db.demo651.insertOne({Value:50});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9f0339e3c3cd0dcff36a5b")
}
> db.demo651.insertOne({Value:60});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9f033be3c3cd0dcff36a5c")
}
> db.demo651.insertOne({Value:70});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9f033ee3c3cd0dcff36a5d")
}
> db.demo651.insertOne({Value:80});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9f0340e3c3cd0dcff36a5e")
}
在find()方法的帮助下显示集合中的所有文档-
> db.demo651.find();
这将产生以下输出-
{ "_id" : ObjectId("5e9f0330e3c3cd0dcff36a57"), "Value" : 10 }{ "_id" : ObjectId("5e9f0332e3c3cd0dcff36a58"), "Value" : 20 }
{ "_id" : ObjectId("5e9f0335e3c3cd0dcff36a59"), "Value" : 30 }
{ "_id" : ObjectId("5e9f0337e3c3cd0dcff36a5a"), "Value" : 40 }
{ "_id" : ObjectId("5e9f0339e3c3cd0dcff36a5b"), "Value" : 50 }
{ "_id" : ObjectId("5e9f033be3c3cd0dcff36a5c"), "Value" : 60 }
{ "_id" : ObjectId("5e9f033ee3c3cd0dcff36a5d"), "Value" : 70 }
{ "_id" : ObjectId("5e9f0340e3c3cd0dcff36a5e"), "Value" : 80 }
以下是获取数据的查询-
> map = function() {...
... if (Math.random() < 0.1) {
... emit(this._id, this);
... }
... }
function () {
if (Math.random() < 0.1) {
emit(this._id, this);
}
}
>
> reduce = function(key, values) {
... return values;
... }
function (key, values) {
return values;
}
>
> db.demo651.mapReduce( map, reduce, { out: 'demo_651' } );
{
"result" : "demo_651",
"timeMillis" : 1104,
"counts" : {
"input" : 8,
"emit" : 1,
"reduce" : 0,
"output" : 1
},
"ok" : 1
}
> db.demo_651.find();
这将产生以下输出-
{ "_id" : ObjectId("5e9f033be3c3cd0dcff36a5c"), "value" : { "_id" : ObjectId("5e9f033be3c3cd0dcff36a5c"), "Value" : 60 } }
以上是 MongoDB查询以使用Map Reduce概念获取随机值。 的全部内容, 来源链接: utcz.com/z/317144.html