由于MongoDB而导致的特定领域?
要在MongoDB中获得特定字段的结果,可以使用findOne()
。以下是语法-
db.yourCollectionName.findOne({"yourFieldName1":yourValue},{yourFieldName2:1});
首先让我们创建一个包含文档的集合-
> db.particularFieldDemo.insertOne({"EmployeeName":"John Smith","EmployeeAge":26,"EmployeeTechnology":"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9b4abb50a6c6dd317ada2") } > db.particularFieldDemo.insertOne({"EmployeeName":"Chris Brown","EmployeeAge":28,"EmployeeTechnology":"Java"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9b4d2b50a6c6dd317ada3") } > db.particularFieldDemo.insertOne({"EmployeeName":"David Miller","EmployeeAge":30,"EmployeeTechnology":"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9b4e8b50a6c6dd317ada4") } > db.particularFieldDemo.insertOne({"EmployeeName":"John Doe","EmployeeAge":31,"EmployeeTechnology":"C++"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9b527b50a6c6dd317ada5") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.particularFieldDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd9b4abb50a6c6dd317ada2"), "EmployeeName" : "John Smith", "EmployeeAge" : 26, "EmployeeTechnology" : "MongoDB" } { "_id" : ObjectId("5cd9b4d2b50a6c6dd317ada3"), "EmployeeName" : "Chris Brown", "EmployeeAge" : 28, "EmployeeTechnology" : "Java" } { "_id" : ObjectId("5cd9b4e8b50a6c6dd317ada4"), "EmployeeName" : "David Miller", "EmployeeAge" : 30, "EmployeeTechnology" : "MySQL" } { "_id" : ObjectId("5cd9b527b50a6c6dd317ada5"), "EmployeeName" : "John Doe", "EmployeeAge" : 31, "EmployeeTechnology" : "C++" }
以下是在MongoDB中查找特定字段作为结果的查询-
> db.particularFieldDemo.findOne({"EmployeeTechnology":"Java"},{EmployeeName:1});
这将产生以下输出-
{ "_id" : ObjectId("5cd9b4d2b50a6c6dd317ada3"), "EmployeeName" : "Chris Brown" }