Querying mongodb from golang using the _id stored in an array

前端 未结 2 394
广开言路
广开言路 2020-12-21 06:50

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 b

相关标签:
2条回答
  • 2020-12-21 06:56

    MongoDB syntax for go.mongodb.org/mongo-driver has been updated, this should work using the official driver.

    oids := make([]primitive.ObjectID, len(ids))
    for i := range ids {
        objID, err := primitive.ObjectIDFromHex(ids[i])
        if err == nil {
            oids = append(oids, objID)
        }
    }
    
    0 讨论(0)
  • 2020-12-21 07:10

    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}}
    
    0 讨论(0)
提交回复
热议问题