我正在尝试使用mgo更新文档数组中的对象。对象结构如下:
/* the lat/lng of the location you are trying to find places nearby */
$lat=56.25;
$lng=-2.65;
$sql="SELECT id, ( 3959 * acos( cos( radians( $lat ) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians($lng) ) + sin( radians($lat) ) * sin( radians( latitude ) ) ) ) AS distance
FROM markers
HAVING distance < 25
ORDER BY distance
LIMIT 0,20;";
查询1:
我首先尝试更新{
"_id": 2,
"status": 0,
"details": [{
"id": 2,
"category": "A",
"obj": {
"apple": 5,
"banana": 2,
"cherry": 10
},
"members": [{
"id": 3,
"category": "A",
"obj": {
"apple": 5,
"banana": 2,
"cherry": 10
}
},
{
"id": 4,
"category": "A",
"obj": {
"apple": 5,
"banana": 2,
"cherry": 10
}
}
]
}]
}
,尝试使用以下查询添加其他属性details > obj
"guava": 15
此查询既不会产生任何错误,也不会更新文档。任何人都可以告诉我怎样才能实现它
注意:我搜索了谷歌,但找不到我需要的内容。
QUERY2:
我还需要以cond := bson.M{ "$and": []bson.M{ bson.M{"document.details":bson.M{ "$elemMatch": bson.M{ "category": "A"} } }, bson.M{"document.status":0} } }
query := bson.M{ "$set": bson.M{ "document.details.$.obj.guava":15 } }
_, err := models.DbUpdateAll(Collection, cond, query)
的方式更新details > members > obj
。还请告诉我如何才能为details > obj
实现相同的目标。
我花了好几个小时来搞清楚这一点,但没有成功。如果有人能指导我,我将感激不尽。
答案 0 :(得分:0)
简单来说,我删除了成员。
package main
import (
"fmt"
"encoding/json"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
func main() {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("test").C("mgo")
cond := bson.M{"$and": []bson.M{bson.M{"details": bson.M{"$elemMatch": bson.M{"category": "A"}}}, bson.M{"status": 0}}}
query := bson.M{"$set": bson.M{"details.$.obj.guava": 15}}
res := []interface{}{}
err = c.Find(cond).All(&res)
if err != nil {
fmt.Println("Before Update Read Error:", err)
return
}
data, _ := json.MarshalIndent(res, "", " ")
fmt.Printf("Before Update Read: %s\n", string(data))
err = c.Update(cond, query)
if err != nil {
fmt.Println("Update Error:", err)
return
}
fmt.Println("Update Succeed!")
err = c.Find(cond).All(&res)
if err != nil {
fmt.Println("After Update Read Error:", err)
return
}
data, _ = json.MarshalIndent(res, "", " ")
fmt.Printf("After Update Read: %s\n", string(data))
}
结果:
Before Update Read: [
{
"_id": 2,
"details": [
{
"category": "A",
"id": 2,
"obj": {
"apple": 5,
"banana": 2,
"cherry": 10
}
}
],
"status": 0
}
]
Update Succeed!
After Update Read: [
{
"_id": 2,
"details": [
{
"category": "A",
"id": 2,
"obj": {
"apple": 5,
"banana": 2,
"cherry": 10,
"guava": 15
}
}
],
"status": 0
}
]