指定 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