dqpd4268
dqpd4268
2016-08-26 08:01

在MongoDB和golang(mgo)中需要在$ push中包含$ each和$ position

已采纳

1.In the back end i m using go lang and for database i use mongoDB. I m trying to find the last document inserted in the embedded array so i can retrieve the document in the last array index without knowing its index.Is is possible?? After researching on this i came to know that its not possible.So i m thinking of using $push,$each and $position.Here i can set the position to 0 so the newly added document will be in 0 so i can retreive it using the index 0.

  Here is bson format
    {
    empid:"L12"
    AnnualLeave:[
        {
        "atotal" : 20,
        }
    ]
    }



 Here is my schema


 type (
            Employee struct {
                EmpId          string
                AnnualLeave    []*AnnualLeaveInfo
            }
             AnnualLeaveInfo struct {
                ATotal          int64   
            }


        I use the mgo statement as follows`enter code here`

 c.Update(bson.M{"empid": "string"}, bson.M{"$push": bson.M{"annualleave":bson.M{"$each":
         bson.M{"atotal": 4},"$position":0}}

2.Please advice me as well how to decrement the ATotal of the previous document attached and keep it as the value of the atotal of the new document. Please help me.Thanks

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doudi7782 doudi7782 5年前

    I m trying to find the last document inserted in the embedded array so i can retrieve the document in the last array index without knowing its index.Is is possible?

    You can find the last array index by derriving from the array length. Using your example:

    type Employee struct {
            EmpId string 
            AnnualLeave []AnnualLeaveInfo
    }
    type AnnualLeaveInfo struct {
            ATotal int64
    }
    
    result := Employee{}
    err = c.Find(bson.M{"empid": "example employee ID"}).One(&result)
    if err != nil {
            log.Fatal(err)
    }
    lastAnnualTotal:= result.AnnualLeave[len(result.AnnualLeave)-1].ATotal
    

    Please advice me as well how to decrement the ATotal of the previous document attached and keep it as the value of the atotal of the new document

    Depending on your use case, you could try performing two database operations:

    • Fetch the last ATotal value from the collection.
    • Push a new AnnualLeaveInfo document with the new ATotal value.
    // Assuming that EmpId is unique
    err = c.Update(bson.M{"empid": result.EmpId},
          bson.M{"$push": bson.M{"annualleave": bson.M{"atotal": int(latestAnnualTotal-1)}}})
    

    If you require atomic updates, see MongoDB Atomicity and Transactions and Model Data for Atomic Operations.

    On another note, it seems that you're trying to do something related to CQRS design patterns. This design pattern may help with calculating your annual leave use case. See also Even Sourcing with MongoDB

    点赞 评论 复制链接分享

相关推荐