MongoDB查询以从文档中获取不同的FirstName值
对于不同的值,请使用distinct()
。让我们创建一个包含文档的集合-
> db.demo303.insertOne({FirstName:"Chris",LastName:"Brown"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e4ea0f6f8647eb59e56202f")
}
> db.demo303.insertOne({FirstName:"John",LastName:"Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4ea104f8647eb59e562030")
}
> db.demo303.insertOne({FirstName:"Chris",LastName:"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4ea10df8647eb59e562031")
}
> db.demo303.insertOne({FirstName:"John",LastName:"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4ea121f8647eb59e562032")
}
> db.demo303.insertOne({FirstName:"David",LastName:"Miller"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e4ea136f8647eb59e562033")
}
在find()
方法的帮助下显示集合中的所有文档-
> db.demo303.find().pretty();
这将产生以下输出-
{"_id" : ObjectId("5e4ea0f6f8647eb59e56202f"),
"FirstName" : "Chris",
"LastName" : "Brown"
}
{
"_id" : ObjectId("5e4ea104f8647eb59e562030"),
"FirstName" : "John",
"LastName" : "Doe"
}
{
"_id" : ObjectId("5e4ea10df8647eb59e562031"),
"FirstName" : "Chris",
"LastName" : "Smith"
}
{
"_id" : ObjectId("5e4ea121f8647eb59e562032"),
"FirstName" : "John",
"LastName" : "Smith"
}
{
"_id" : ObjectId("5e4ea136f8647eb59e562033"),
"FirstName" : "David",
"LastName" : "Miller"
}
以下是获取不同的FirstName值的查询-
> db.demo303.distinct("FirstName");
这将产生以下输出-
[ "Chris", "John", "David" ]
以上是 MongoDB查询以从文档中获取不同的FirstName值 的全部内容, 来源链接: utcz.com/z/316141.html