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

Get array objects with specific ObjectId in nested array

我正在尝试根据对象的 ObjectId 获取特定的对象数组。

这是我的 MongoDB 数据库:

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

MongoDB中的命令是:

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

这将起作用并且 return 数组将被正确过滤。 我想用 Golang 翻译这个查询。

这是我的代码:

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)
}

我收到类似 wrong type for field (pipeline) 3 != 4 的错误。我看到 $all 需要字符串数组,但如何按 ObjectId 而不是字符串进行过滤?

感谢帮助

您正试图在 mgo 解决方案中使用聚合框架,但您尝试实现的查询并未使用(也不需要)。

查询:

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

可以像这样简单地转换为mgo

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)

另请注意,如果您将 $all 与单个元素一起使用,您还可以使用 $elemMatch 实现该查询,在 MongoDB 控制台中会像这样:

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

mgo 中看起来像这样:

err := c.Find(bson.M{"userids": bson.M{
    "$elemMatch": bson.M{"$eq": bson.ObjectIdHex("59edb459593904117884b71f")},
}}).All(&objects)