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

发布时间:2020-08-10 19:14:59 作者:chenfeng
来源:ITPUB博客 阅读:358

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


推荐阅读:
  1. oracle 如何随机取表中n条记录?
  2. sql分组查询每组的第一条记录

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mongodb 一条 查询

上一篇:11GR2RAC丢失OCR和CONTROLFILE重建恢复过程

下一篇:教你如何在 Ubuntu 中安装 Oracle Java 13

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》