1

I try to insert data from a variable and can't find a way to do this, can someone help me? something like this:

name = "mark"
surname = "clark"

db.collection('user').insert([{'username': @name, 'usersurname': @surname}])

thanks!

Stanislav Kralin
  • 11,070
  • 4
  • 35
  • 58
yiya
  • 11
  • 1

2 Answers2

0

The "db.collection.insert" function is intended to work with objects/arrays, and does not support "variables" as such. In this case, you would use some sort of loop:

list_of_persons = [ {name: 'mark', surname: 'clark'} ]
for p in list_of_persons:
    db.collection('user').insert({'username': p.name, 'usersurname': p.surname})

Since variables are an AQL construct, they only supported in the query/cursor interface. Here you can specify the variable in the AQL (like @myVar) and specify a "bind variable" in the body of the call. You will have to read the docs for specific implementation, as they all differ slightly.

kerry
  • 757
  • 6
  • 16
  • Thanks for your answer, I have to study the documentation better but I'm starting out and the desire to try is too much. however I get this error "SyntaxError: unexpected EOF while parsing". I read that it may be a loop problem but I don't understand which ... any suggestions? – yiya May 19 '20 at 21:24
  • That sounds like a Python problem, not specifically related to ArangoDB. Make sure the line-endings in your file are correct (CRLF on Win, LF on *nix, CR on Mac) or the Python interpreter may throw an EOF. Also, try taking out any "do it" logic (e.g insert/query/update/etc.) and just have it parse basic constructs and loops first. – kerry May 19 '20 at 23:07
0

Your usage of @name and @surname is correct. What is missing is a call to a bind_vars dictionary in the AQL method. This will map the @ variables to their python variable values.

Here is your code using an alternative syntax. You will notice that I took the liberty to declare a collection variable as well; why not?

name = "mark"
surname = "clark"
collection = "user"

bind = {"@collection": collection, "name": name, "surname": surname}
aql = "INSERT {username: @name, usersurname: @surname} INTO @@collection"
query = db.aql.execute(aql, bind_vars=bind)

Note the single @ in front of variable names, but @@ in front of a collection name. In the bind dictionary, 0 and 1 @, respectively.

SebM
  • 1
  • 1