MongoDB如何根据条件查找记录
要根据条件查找MongoDB,请使用find()并设置条件。让我们创建一个包含文档的集合-
> db.demo708.insertOne({"Name":"John",Marks:54}); { "acknowledged" : true, "insertedId" : ObjectId("5ea702e4d346dcb074dc6f33") } > db.demo708.insertOne({"Name":"Chris",Marks:35}); { "acknowledged" : true, "insertedId" : ObjectId("5ea702e6d346dcb074dc6f34") } > db.demo708.insertOne({"Name":"David",Marks:45}); { "acknowledged" : true, "insertedId" : ObjectId("5ea702ebd346dcb074dc6f35") } > db.demo708.insertOne({"Name":"Bob",Marks:40}); { "acknowledged" : true, "insertedId" : ObjectId("5ea702fad346dcb074dc6f36") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo708.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea702e4d346dcb074dc6f33"), "Name" : "John", "Marks" : 54 } { "_id" : ObjectId("5ea702e6d346dcb074dc6f34"), "Name" : "Chris", "Marks" : 35 } { "_id" : ObjectId("5ea702ebd346dcb074dc6f35"), "Name" : "David", "Marks" : 45 } { "_id" : ObjectId("5ea702fad346dcb074dc6f36"), "Name" : "Bob", "Marks" : 40 }
以下是根据条件查找MongoDB记录的查询-
> db.demo708.find({Marks:{$gt:40}});
这将产生以下输出-
{ "_id" : ObjectId("5ea702e4d346dcb074dc6f33"), "Name" : "John", "Marks" : 54 } { "_id" : ObjectId("5ea702ebd346dcb074dc6f35"), "Name" : "David", "Marks" : 45 }