如何查询 MongoDB 集合?
要查询或返回 MongoDB 集合,请使用 getCollection()。我们创建一个带有文档的集合 −
> db.demo294.insertOne({"EmployeeId":101,"EmployeeName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4d4a1a5d93261e4bc9ea36") } > db.demo294.insertOne({"EmployeeId":102,"EmployeeName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4d4a255d93261e4bc9ea37") } > db.demo294.insertOne({"EmployeeId":103,"EmployeeName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e4d4a335d93261e4bc9ea38") }
使用 find() 方法显示来自集合的所有文档 −
> db.demo294.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e4d4a1a5d93261e4bc9ea36"), "EmployeeId" : 101, "EmployeeName" : "Chris" } { "_id" : ObjectId("5e4d4a255d93261e4bc9ea37"), "EmployeeId" : 102, "EmployeeName" : "Bob" } { "_id" : ObjectId("5e4d4a335d93261e4bc9ea38"), "EmployeeId" : 103, "EmployeeName" : "David" }
以下是获取 MongoDB 集合的查询 −
> db.getCollection('demo294').find({ ... "EmployeeId":{$in:[101,103]}});
这将产生以下输出 −
{ "_id" : ObjectId("5e4d4a1a5d93261e4bc9ea36"), "EmployeeId" : 101, "EmployeeName" : "Chris" } { "_id" : ObjectId("5e4d4a335d93261e4bc9ea38"), "EmployeeId" : 103, "EmployeeName" : "David" }
广告