N1ql Select Document by document KEY Golang

Hello! I’m modeling a document in Go for Couchbase and I have this struct:

type User struct {
  ID                 string `json:"id"`
  Type            string `json:"type"`
  Username   string `json:"username"` 
}

When I save a new document, I use this method:

_, err = Bucket.Insert("user_xxxx", User{
		ID:               "uuid",
            Type:          "user",
		Username:  "username",
	}, 0)

Now How do I query these data by key?

Currently I select with this: SELECT * FROM bucketname WHERE type="user" and username=$1"

Is there a way to select by document key (since I have an ID in the struct)?

SELECT META().id AS ID, * FROM bucketname WHERE type="user" and username=$1

1 Like

Thanks, one more thing, Since theres a field in the document saved with _id which is a generated unique id, when I need to do a relationship doc, do I use the _id or the document key?

document key. META().id gives document key, _id inside document is like any other field in the document

1 Like

Also, in N1QL, you can write a query to RETURN the meta().id.

INSERT INTO bucketname VALUES(“USER_2982”, {“a”:32})
RETURNING META().id;

@ingenthr, @daschl: is there a method in the golang API do everything in a single call?

1 Like

I’m not sure I follow the question @keshav_m. If you have the document including the key already in scope, there’s no real reason to have a function to get it. It’s not quite the same as the N1QL statement, since you’d normally use the API which is built to use the structs defined in golang or []interface{} when working with N1QL query responses.

1 Like