MongoDB随机查询返回一条或N条记录的方法

用$sample (aggregation)方法,具体命令为:

db.collection.aggregate( [ { $sample: { size: N } } ] ) N为条数

例如返回5条:

> db.test.aggregate( [ { $sample: { size: 5 } } ] )

{ "_id" : ObjectId("5d1c5a7b39ab0f9fbcd647a8"), "id" : 1, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c733bee9b8d3cbbc26779"), "id" : 89007, "name" : "hello" }

{ "_id" : ObjectId("5d1c7342ee9b8d3cbbc276dc"), "id" : 92946, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c7240df7032c6c7966207"), "id" : 88223, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5b7c39ab0f9fbcd94c62"), "id" : 97819, "name" : "chenfeng" }


返回1条:

> db.test.aggregate( [ { $sample: { size: 1 } } ] )

{ "_id" : ObjectId("5d1c5aec39ab0f9fbcd7b29a"), "id" : 92915, "name" : "chenfeng" }

返回15条:

> db.test.aggregate( [ { $sample: { size: 15 } } ] )

{ "_id" : ObjectId("5d1c5b4039ab0f9fbcd88eca"), "id" : 49283, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5b6539ab0f9fbcd904f3"), "id" : 79532, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5b8a39ab0f9fbcd979b3"), "id" : 109420, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5c8239ab0f9fbcdc5229"), "id" : 295906, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c6d9adf7032c6c7939435"), "id" : 4461, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c6bf3eb9134288dc9f3ef"), "id" : 79051, "name" : "dsf" }

{ "_id" : ObjectId("5d1c6bc0eb9134288dc98769"), "id" : 51269, "name" : "dsf" }

{ "_id" : ObjectId("5d1c72c4ee9b8d3cbbc1698d"), "id" : 24003, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c6de8df7032c6c794a42a"), "id" : 74082, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c6dfddf7032c6c794eecf"), "id" : 93191, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5d1839ab0f9fbcde28a5"), "id" : 416350, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5cbe39ab0f9fbcdd0dad"), "id" : 343910, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5c0639ab0f9fbcdaed91"), "id" : 204618, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5bd639ab0f9fbcda637d"), "id" : 169270, "name" : "chenfeng" }

{ "_id" : ObjectId("5d1c5c9639ab0f9fbcdc8fb7"), "id" : 311664, "name" : "chenfeng" }


相关文章

这篇文章主要介绍“hive和mysql的区别是什么”,在日常操作中...
这篇“MySQL数据库如何改名”文章的知识点大部分人都不太理解...
这篇文章主要介绍“mysql版本查询命令是什么”的相关知识,小...
本篇内容介绍了“mysql怎么修改字段的内容”的有关知识,在实...
这篇文章主要讲解了“mysql怎么删除unique约束”,文中的讲解...
今天小编给大家分享一下mysql怎么查询不为空的字段的相关知识...