使用存储在数组中的_id从golang查询mongodb [英] Querying mongodb from golang using the _id stored in an array

查看:296
本文介绍了使用存储在数组中的_id从golang查询mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我的问题。我有一个数组存储了 _ids 的mongodbs对象。什么是使用mgo和bson包在一个查询中检索它们的正确方法?

所以如果数组是这样的: ids:= [543d171c5b2c12420dd016,543d171c5b2dd016]



我们如何进行查询?我试过,但我知道它是错的。

  query:= bson.M {_ id:bson.M {$ in:ids}} 
c.Find(query).All()

提前

解决方案

如果文档与字符串ID保存在一起,那么代码看起来是正确的。



这些ID看起来像十六进制编码的对象ID。如果对象标识符是对象标识符,那么您需要将十六进制字符串转换为对象标识符:

  oids:= make [] bson.ObjectId,len(ids))
for i:= range ids {
oids [i] = bson.ObjectIdHex(ids [i])
}
查询:= bson.M {_ id:bson.M {$ in:oids}}


So here is my question. I have an array which are stored the _ids of mongodbs objects. Whats the right way to retrieve them all in one query using the mgo and bson package?

So if the array is like that: ids:=["543d171c5b2c12420dd016","543d171c5b2dd016"]

How we make the query ? I tried that but I know its wrong.

query := bson.M{"_id": bson.M{"$in": ids}}
c.Find(query).All()

Thanks in advance

解决方案

If the documents are stored with string ids, then the code looks correct.

The ids look like hex encoded object ids. If the object identifiers are object ids, then you need to the convert the hex strings to object ids:

oids := make([]bson.ObjectId, len(ids))
for i := range ids {
  oids[i] = bson.ObjectIdHex(ids[i])
}
query := bson.M{"_id": bson.M{"$in": oids}}

这篇关于使用存储在数组中的_id从golang查询mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆