我试图根据他们拥有的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") ] }
} )
这将起作用并将返回正确过滤的数组。 我想在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而不是字符串过滤?
感谢您的帮助
答案 0 :(得分:2)
您正在尝试在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)