How to insert a document if a filter returns nothing, otherwise replace the document found in mongodb with go? - database

I am not using the MGO package like in this example, just the active repo from here.
I am having a hard time reading the documentation. Basically, I have a bson.M object that I want to replace the current one, and if that one doesn't exist, insert it.
Currently my code looks like:
updateFilter := bson.D{{"from_symbol", fromSymbol}, {"to_symbol", strings.ToUpper(currency["to_symbol"].(string))}}
// The above seems to be correctly finding the documents I want
// currency is my bson.M object
_, err := collection.ReplaceOne(ctx, updateFilter, currency)
// However this line will not additionally insert if the object is not found, it is replacing fine
I'm sure I could manually run another query looking to see if the document exists, but that seems unnecessary.
Thank you!
EDIT:
It looks like there should be a way to do something with replaceOptions, see the documentation.
upsert := options.ReplaceOptions{Upsert: true}
_, err := collection.ReplaceOne(ctx, updateFilter, currency, upset)
However this gives me the error:
cannot use true (type bool) as type *bool in field value

Use the SetUpsert function:
collection.ReplaceOne(ctx,filter,newDoc,options.Replace().SetUpsert(true))

Related

Inserting `sql.Nulltime` into Postgres `timestamp with time zone`

Let's s say I have struct with a field like:
FinishedAt sql.NullTime `json:"finished_at"`
var out models.Job
err := client.QueryRow(ctx, updateQuery,
&job.FinishedAt,
).Scan(
&out.FinishedAt,
)
Above I use "github.com/jackc/pgx/v4" to work with PG.
There is no error during the update but the field is set to null after the request.
Using &job.FinishedAt.Time as an argument works appropriately but I want to understand why the sql.Nulltime type doesn't work.
Is that just related to how the library works?

How to access map values in golang

When I perform a POST request it sends the raw-data like below.
products%5B%22producs-1%22%5D%5B%22pink%22%5D%3D1%26products%5B%22products-2%22%5D%5B%22black%22%5D%3D2%26products%5B%22products-3%22%5D%5B%22green%22%5D%3D2%27
When I do URL ParseQuery it shows output like this:
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
fmt.Println(string(body))
params, _ := url.ParseQuery(string(body))
fmt.Println(params)
map[products["products-1"]["black"]:[2] products["products-2"]["green"]:[2] products["products-3"]["pink"]:[1]]
I want to access products-1, black, 2(other fields also), how can I do this?
That is a rather strange format and looks like it is expecting a PHP script. Or some other scripting language.
The ParseQuery function has made a map but the key is a string that looks like "products["products-2"]["green"]"
I assume it would be better to have a "products" map that contains an "attributes" map or something like that. I'm not sure how to get there without a lot of effort
try loop by keys to get what are the keys:
for k, v := range params {
fmt.Printf("key[%s] value[%s]\n", k, v)
}

Parsing and converting JSON

I have an issue with TJSONObject.ParseJSONValue or TJSONObject.toString
the following code does not display the JSON from Memo1 in Memo2, only an empty "{}":
A:=tJSONObject.Create;
A.ParseJSONValue(Memo1.Lines.Text);
Memo2.Lines.Text:=A.ToString;
What is wrong with it?
ParseJSONValue() is a class function of TJSONObject. It does not modify the TJSONObject that it is called on, like you are expecting. It returns a new TJSONValue, which will point to a TJSONObject if the JSON data represents a JSON object. You are ignoring that return value (and thus leaking it, as you need to call Free on it with you are done using it).
You need to change your code to something more like this:
var A: TJSONValue;
A := TJSONObject.ParseJSONValue(Memo1.Text);
if A <> nil then
try
Memo2.Text := A.ToString;
finally
A.Free;
end;
ParseJSONValue is a FUNCTION so it needs to be
A:=A.ParseJSONValue...
how stupid....

MongoDB slice query into golang

How can i write this below slice query into golang?
db.con.find({"repoid":1356485},{"contr":{$slice:[0,10]}}).pretty()
Tried with this but not working
DB.C("con").Find(bson.M{"id": ID, "contr": bson.M{"$slice": []interface{}{"$contr", offset, limit}}})
does not find anything. Any ideas?
Thank you in advance
With Collection.Find() you can only specify the filter. But what you have is a projection:
{"contr":{$slice:[0,10]}
Projections can be specified using Query.Select(), so this is how you can apply a $slice in projection:
var results []bson.M // Use your own type here, but this works too
err := DB.C("con").Find(bson.M{"id": ID}).Select(bson.M{
"contr": bson.M{"$slice": []int{offset, limit}},
}).All(&results)
// handle error
Also note sure if the property you filter by is "id" or is just a typo and it should be "_id". If the latter, you may also use Collection.FindId() to query by document ID:
err := DB.C("con").FindId(ID).Select(bson.M{
"contr": bson.M{"$slice": []int{offset, limit}},
}).All(&results)

Delphi XE10 Filtering database table using FORMAT LIKE

I want filtering my database using fdtable. I write this code fdtable2.Filter := Format('PRODUK LIKE ''%s%%''', [edit1.Text]); but it was so sensitive with Uppercase and Lowercase. How can i write the code so when i write 'emon' in the edit.text, it filtering the word like 'Lemon' into the database. Thank you
Have you added the
fdtable2.Filtered := true;
in your Code?
You also have a mistake in your code!
fdtable2.Filter := Format('PRODUK LIKE ''%s%%''', [edit1.Text]);
This Code will Result in "PRODUK LIKE 'SOME_TEXT%%'"
you should set the s to the right Position to get it work properly.
This should work:
fdtable2.Filter := Format('PRODUK LIKE ''%%s%''', [edit1.Text]);
fdtable2.Filtered := true;

Resources