我试图通过HTTP接口删除MongoLab服务中托管的MongoDb数据库中的集合中的多个文档。这是我试图实现它的CURL请求
curl -H "Content-Type: application/json" -X PUT "https://api.mongolab.com/api/1/databases/mydb/collections/mycoll?q={\"person\":\"554b3d1ae4b0e2832aeeb6af\"}&apiKey=xxxxxxxxxxxxxxxxx"
我基本上希望从集合中删除具有匹配查询的所有文档。
http://docs.mongolab.com/restapi/#view-edit-delete-document的Mongolab文档建议"Specifying an empty list in the body is equivalent to deleting the documents matching the query."
。但是我如何在PUT请求体中发送空列表?
以下是用于实现上述PUT请求的Golang代码
client := &http.Client{}
postRequestToBeSentToMongoLab, err := http.NewRequest("PUT","https://api.mongolab.com/api/1/databases/mydb/collections/mycoll?q={\"person\":\"554b3d1ae4b0e2832aeeb6af\"}&apiKey=xxxxxxxxxxxxxxxxx",nil )
postRequestToBeSentToMongoLab.Header.Set("Content-Type", "application/json") //http://stackoverflow.com/questions/24455147/go-lang-how-send-json-string-in-post-request
responseFromMongoLab, err := client.Do(postRequestToBeSentToMongoLab)
在两种情况下返回null
(Golang和CURL的PUT请求的情况)。如何使其工作,以便删除与查询匹配的所有文档?
答案 0 :(得分:0)
我想你需要传递一个空的json数组作为PUT消息的有效载荷。有了curl,它就像是:
curl -H "Content-Type: application/json" -X PUT -d '[]' "https://api.mongolab.com/api/1/databases/mydb/collections/mycoll?q={\"person\":\"554b3d1ae4b0e2832aeeb6af\"}&apiKey=xxxxxxxxxxxxxxxxx"
在Go代码中,您需要编写如下内容:
client := &http.Client{}
req, err := http.NewRequest(
"PUT",
"https://api.mongolab.com/api/1/databases/mydb/collections/mycoll?q={\"person\":\"554b3d1ae4b0e2832aeeb6af\"}&apiKey=xxxxxxxxxxxxxxxxx",
bytes.NewBuffer("[]")
)
req.Header.Set("Content-Type", "application/json")
reply, err := client.Do(req)