从MongoDB获取随机记录?

要从MongoDB获取随机记录,可以使用聚合函数。语法如下:

db.yourCollectionName.aggregate([{$sample:{size:1}}]);

为了理解上述语法,让我们创建包含一些文档的集合。创建集合的查询如下:

>db.employeeInformation.insert({"EmployeeId":1,"EmployeeName":"Maxwell","EmployeeAge":26});

WriteResult({ "nInserted" : 1 })

>db.employeeInformation.insert({"EmployeeId":2,"EmployeeName":"David","EmployeeAge":25});

WriteResult({ "nInserted" : 1 })

>db.employeeInformation.insert({"EmployeeId":3,"EmployeeName":"Carol","EmployeeAge":24});

WriteResult({ "nInserted" : 1 })

>db.employeeInformation.insert({"EmployeeId":4,"EmployeeName":"Bob","EmployeeAge":28});

WriteResult({ "nInserted" : 1 })

>db.employeeInformation.insert({"EmployeeId":5,"EmployeeName":"Sam","EmployeeAge":27);

WriteResult({ "nInserted" : 1 })

现在,您可以借助find()method显示集合中的所有文档。查询如下:

> db.employeeInformation.find().pretty();

以下是输出:

{

   "_id" : ObjectId("5c6d3079734e98fc0a434ae5"),

   "EmployeeId" : 1,

   "EmployeeName" : "Maxwell",

   "EmployeeAge" : 26

}

{

   "_id" : ObjectId("5c6d308c734e98fc0a434ae6"),

   "EmployeeId" : 2,

   "EmployeeName" : "David",

   "EmployeeAge" : 25

}

{

   "_id" : ObjectId("5c6d309d734e98fc0a434ae7"),

   "EmployeeId" : 3,

   "EmployeeName" : "Carol",

   "EmployeeAge" : 24

}

{

   "_id" : ObjectId("5c6d30ab734e98fc0a434ae8"),

   "EmployeeId" : 4,

   "EmployeeName" : "Bob",

   "EmployeeAge" : 28

}

{

   "_id" : ObjectId("5c6d30bb734e98fc0a434ae9"),

   "EmployeeId" : 5,

   "EmployeeName" : "Sam",

   "EmployeeAge" : 27

}

这是获取随机记录的查询:

> db.employeeInformation.aggregate([{$sample:{size:1}}]).pretty();

以下是输出:

{

   "_id" : ObjectId("5c6d30bb734e98fc0a434ae9"),

   "EmployeeId" : 5,

   "EmployeeName" : "Sam",

   "EmployeeAge" : 27

}

让我们使用相同的查询获得另一个随机记录:

> db.employeeInformation.aggregate([{$sample:{size:1}}]).pretty();

以下是输出:

{

   "_id" : ObjectId("5c6d308c734e98fc0a434ae6"),

   "EmployeeId" : 2,

   "EmployeeName" : "David",

   "EmployeeAge" : 25

}

以上是 从MongoDB获取随机记录? 的全部内容, 来源链接: utcz.com/z/316112.html

回到顶部