指定 MongoDB 中的数据的返回格式
借助 MongoDB 中的 $addToSet 来指定返回格式。我们来创建一个包含文档的集合 -
> db.demo207.insertOne({"FavouriteTechnology":"Spring Boot"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3d8e7a03d395bdc21346f1")
}
> db.demo207.insertOne({"FavouriteTechnology":"MongoDB"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3d8e8f03d395bdc21346f2")
}
> db.demo207.insertOne({"FavouriteTechnology":"Groovy"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3d8ea603d395bdc21346f3")
}在集合中使用 find() 方法显示所有文档 -
> db.demo207.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e3d8e7a03d395bdc21346f1"), "FavouriteTechnology" : "Spring Boot" }
{ "_id" : ObjectId("5e3d8e8f03d395bdc21346f2"), "FavouriteTechnology" : "MongoDB" }
{ "_id" : ObjectId("5e3d8ea603d395bdc21346f3"), "FavouriteTechnology" : "Groovy" }以下是指定返回格式的查询 -
> db.demo207.aggregate([
... {
... "$group": {
... "_id": 0,
... "FavouriteTechnology": {
... "$addToSet": "$FavouriteTechnology"
... }
... }
... },
... {
... "$project": {
... "_id": 0,
... "FavouriteTechnology": 1
... }
... }
...]);这将产生以下输出 -
{ "FavouriteTechnology" : [ "MongoDB", "Groovy", "Spring Boot" ] }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP