dongshedan4672 2017-10-23 14:38 采纳率: 0%
浏览 210
已采纳

在嵌套数组中获取具有特定ObjectId的数组对象

I'm trying to get a specific array of objects depending on ObjectId they have.

Here is my MongoDB database:

{
    "_id" : ObjectId("59edb571593904117884b721"),
    "userids" : [
            ObjectId("59edb459593904117884b71f")
    ],
    "macaddress" : "MACADDRESS",
    "devices" : [ ],
    "projectorbrand" : "",
}
{
    "_id" : ObjectId("59edb584593904117884b722"),
    "userids" : [
            ObjectId("59edb459593904117884b71f"),
            ObjectId("59e4809159390431d44a9438")
    ],
    "macaddress" : "MACADDRESS2",
    "devices" : [ ],
    "projectorbrand" : "",
}

The command in MongoDB is:

db.getCollection('co4b').find( {
    userids: { $all: [ ObjectId("59edb459593904117884b71f") ] }
} )

This will work and will return an array filtered correctly. I would like to translate this query in Golang.

Here is my code:

pipe := bson.M{"userids": bson.M{"$all": objectId}}
var objects[]models.Objects
if err := uc.session.DB("API").C("objects").Pipe(pipe).All(&objects); err != nil {
    SendError(w, "error", 500, err.Error())
} else {
    for i := 0; i < len(objects); i++ {
        objects[i].Actions = nil
    }
    uj, _ := json.MarshalIndent(objects, "", " ")
    SendSuccessJson(w, uj)
}

I'm getting error like wrong type for field (pipeline) 3 != 4. I saw that $all needs string array but how to filter by ObjectId instead of string?

Thanks for help

  • 写回答

1条回答 默认 最新

  • donglong2856 2017-10-23 20:37
    关注

    You are attempting to use the aggregation framework in your mgo solution, yet the query you try to implement does not use one (and does not need one).

    The query:

    db.getCollection('co4b').find({
        userids: {$all: [ObjectId("59edb459593904117884b71f")] }
    })
    

    Can simply be transformed to mgo like this:

    c := uc.session.DB("API").C("objects")
    
    var objects []models.Objects
    err := c.Find(bson.M{"userids": bson.M{
        "$all": []interface{}{bson.ObjectIdHex("59edb459593904117884b71f")},
    }}).All(&objects)
    

    Also note that if you're using $all with a single element, you can also implement that query using $elemMatch, which in MongoDB console would like this:

    db.getCollection('co4b').find({
        userids: {$elemMatch: {$eq: ObjectId("59edb459593904117884b71f")}}
    })
    

    Which looks like this in mgo:

    err := c.Find(bson.M{"userids": bson.M{
        "$elemMatch": bson.M{"$eq": bson.ObjectIdHex("59edb459593904117884b71f")},
    }}).All(&objects)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格