I am attempting to convert the following MongoDB JSON command into valid BSON using the Mongo C driver:
db.test.update({
"_id" : ObjectId("5624200d4bacd3940b8b2d62"),
"folders.folder_id": "3_root",
"folders.files": { $elemMatch: { "file": "5BD252AD-10C9-4DCE-A59C-5E3223BDDC60"}} },
{$inc : { "folders.0.files.$.favorites.0.like": 1} }
);
I have attempted to create it using:
query = BCON_NEW ("_id", BCON_OID(&oid));
BSON_APPEND_UTF8 (query, "folders.folder_id", folderPositionRaw);
BSON_APPEND_UTF8 (query, "folders.files", "{" , "$elemMatch","{","file","5BD252AD-10C9-4DCE-A59C-5E3223BDDC60","}","}");
update = BCON_NEW ("$inc",
"{",
"folders.0.files.$.favorites.0.like", 1,
"}");
mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error);
But it is way wrong.
When I compile I get:
/current/set_fav.c: In function ‘main’:
/current/set_fav.c:102: warning: initialization discards qualifiers from pointer target type
/current/set_fav.c:168:122: error: macro "BSON_APPEND_UTF8" passed 9 arguments, but takes just 3
/current/set_fav.c:168: error: ‘BSON_APPEND_UTF8’ undeclared (first use in this function)
/current/set_fav.c:168: error: (Each undeclared identifier is reported only once
/current/set_fav.c:168: error: for each function it appears in.)
FYI: folderPositionRaw has the value of 3_root set higher up in the codes.
To add a little more information: Originally I had the wrong Mongo syntax, but C was happy. I was using the following:
query = bson_new ();
bson_oid_init_from_string (&oid, tribe_id);
query = BCON_NEW ("_id", BCON_OID(&oid));
BSON_APPEND_UTF8 (query, "folders.folder_id", folderPositionRaw);
BSON_APPEND_UTF8 (query, "folders.folder_id.$.files.file", file);
I received help from my DB team giving me the correct Mongo syntax (top of post) and in my attempt to structure that into the C BSON I did something wrong.
Some progress:
I have updated my codes and they NO longer crash which is a good sign, but the output JSON that is sent to Mongo is not fully structured correctly. I think the issue is the value 1 that is sent in the mongo $inc command is being sent as a scalar 1 not an int 1. I have tried both with and without quotes around the 1. With quotes the code runs, but does not preform the update (no errors returned). If I remove the quotes the app crashes.
query = bson_new ();
bson_oid_init_from_string (&oid, tribe_id);
query = BCON_NEW ("_id", BCON_OID(&oid), "folders.folder_id", folderPositionRaw,"folders.files",
"{",
"$elemMatch",
"{",
"file", file,
"}",
"}");
// Find the document
cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);
// update document
update = BCON_NEW ("$inc",
"{",
"folders.0.files.$.favorites.0.like","1",
"}");
str = bson_as_json (update, NULL);
printf ("***-> %s <-***\n\n",str);
mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error);
Found the issue!
You cannot use a standard int it must be a BCON_INT
update = BCON_NEW ("$inc",
"{",
"folders.0.files.$.favorites.0.like",BCON_INT32 (1),
"}");
:)
Related
I want to create a for loop when the variable is in a string format.
my code is:
for i in range(1,32):
DEP_RATE = pd.read_sql_query('select DAYNUM,YYYYMM,sum(DEP_RATE) from ASPM.aspm_qtr where LOCID="ABQ" and DAYNUM = i:"{i}" group by YYYYMM',{i:str(i)},rconn)
the error is:
'dict' object has no attribute 'cursor'
I used this code:
for i in range(1,32):
DEP_RATE = pd.read_sql_query('select DAYNUM,YYYYMM,sum(DEP_RATE) from ASPM.aspm_qtr where LOCID="ABQ" and DAYNUM = "i" group by YYYYMM',rconn, params={i:str(i)})
It hasn't error but doesn't work. the problem is:
("Truncated incorrect DOUBLE value: 'i'")
This appears to be a PANDAS question, yes? I believe it's an argument mismatch with the read_sql_query API. The function signature is:
pandas.read_sql_query(sql, con, index_col=None, coerce_float=True, params=None, parse_dates=None, chunksize=None)
Which roughly says that the first two positional arguments are required, and everything else is defaulted or optional.
To make it more obvious, consider putting your core SQL string on a separate line:
sql = 'SELECT daynum, ... AND daynum = :i'
for i in range(1, 32):
DEP_RATE = pd.read_sql_query(sql, {i: str(i)}, rconn)
With this formulation, it's more obvious that your arguments do not match the API: your second argument is off. Perhaps you want (note the additional keyword argument params):
DEP_RATE = pd.read_sql_query(sql, rconn, params={i: str(i)})
I corrected the code. The correct answer is:
DEP_RATE = list(np.zeros((1,1)))*31
for i in range(1,32):
DEP_RATE[i-1] =np.array(pd.read_sql_query('select DAYNUM,YYYYMM,sum(DEP_RATE) from ASPM.aspm_qtr where LOCID="ABQ" and DAYNUM = '+str(i)+' group by YYYYMM;',rconn, params={i:str(i)}))
I've been doing this for a couple of days, and I'm having this problem:
Whenever I try to encode a map into query string, I get the error "syntax error before: chat_id"
form = %{
"chat_id" => 237799109,
"text" => "OMG a message"
}
{status, body} = URI.encode_query(form)
#=> (SyntaxError) lib/elixir.ex:20: syntax error before: chat_id
But as far as I know this is the map syntax, isn't it? As seen here, where this example is presented:
iex> hd = %{"foo" => 1, "bar" => 2}
iex> URI.encode_query(hd)
"bar=2&foo=1
What is happening here?
Full error message:
== Compilation error on file lib/elixir.ex ==
** (SyntaxError) lib/elixir.ex:20: syntax error before: chat_id
(elixir) lib/kernel/parallel_compiler.ex:117: anonymous fn/4 in Kernel.Paral
lelCompiler.spawn_compilers/1
I don't know why you would get the error you listed, but URI.encode_query/1 only returns a single binary argument. You are trying to pattern match it against a tuple.
Can you paste more of the code instead of just those 2 lines?
iex(2)> URI.encode_query(form)
"chat_id=237&text=OMG+a+message"
I am not able to get error details using the PQresultErrorField API after a query execution fails. Using PQerrorMessage on the connection gives the correct error (constraint violation xxx_pk etc etc) and PQresultStatus shows FATAL_ERROR.
However, when I use the API PQresultErrorField(result, PG_DIAG_SQLSTATE)), I get a NULL result. Other field-codes also gives me null results.
Does this API need to be compiled in ?
Postgres version is 9.2.1
Using libpq C library
It's supposed to return NULL only when it's not applicable.
That simple test works for me:
PGresult* res = PQexec(conn, "SELECT * FROM foobar");
if (res) {
if (PQresultStatus(res) == PGRES_FATAL_ERROR) {
char* p = PQresultErrorField(res, PG_DIAG_SQLSTATE);
if (p) {
printf("sqlstate=%s\n", p?p:"null");
}
}
}
Result:
sqlstate=42P01
Here is my selection code from db:
$q = $this->db->like('Autor1' or 'Autor2' or 'Autor3' or 'Autor4', $vyraz)
->where('stav', 1)
->order_by('id', 'desc')
->limit($limit)
->offset($offset)
->get('knihy');
return $q->result();
Where $vyraz = "Zuzana Šidlíková";
And the error is:
Nastala chyba databázy
Error Number: 1054
Unknown column '1' in 'where clause'
SELECT * FROM (\knihy`) WHERE `stav` = 1 AND `1` LIKE '%Zuzana Ĺ idlĂková%' ORDER BY `id` desc LIMIT 9
Filename: C:\wamp\www\artbooks\system\database\DB_driver.php
Line Number: 330
Can you help me solve this problem?
Your syntax is wrong for what you're trying to do, but still technically valid, because this:
'Autor1' or 'Autor2' or 'Autor3' or 'Autor4'
...is actually a valid PHP expression which evaluates to TRUE (because all non-empty strings are "truthy"), which when cast to a string or echoed comes out as 1, so the DB class is looking to match on a column called "1".
Example:
function like($arg1, $arg2)
{
return "WHERE $arg1 LIKE '%$arg2%'";
}
$vyraz = 'Zuzana Šidlíková';
echo like('Autor1' or 'Autor2' or 'Autor3' or 'Autor4', $vyraz);
// Output: WHERE 1 LIKE '%Zuzana Šidlíková%'
Anyways, here's what you need:
$q = $this->db
->like('Autor1', $vyraz)
->or_like('Autor2', $vyraz)
->or_like('Autor3', $vyraz)
->or_like('Autor4', $vyraz)
->where('stav', 1)
->order_by('id', 'desc')
->limit($limit)
->offset($offset)
->get('knihy');
I'd like to know if a record is present in a database, using a field different from the key field.
I've try the following code :
function start()
{
jlog("start db query")
myType d1 = {A:"rabbit", B:"poney"};
/myDataBase/data[A == d1.A] = d1
jlog("db write done")
option opt = ?/myDataBase/data[B == "rabit"]
jlog("db query done")
match(opt)
{
case {none} : <>Nothing in db</>
case {some:data} : <>{data} in database</>
}
}
Server.start(
{port:8092, netmask:0.0.0.0, encryption: {no_encryption}, name:"test"},
[
{page: start, title: "test" }
]
)
But the server hang up, and never get to the line jlog("db query done"). I mispell "rabit" willingly. What should I've done ?
Thanks
Indeed it fails with your example, I have a "Match failure 8859742" exception, don't you see it?
But do not use ?/myDataBase/data[B == "rabit"] (which should have been rejected at compile time - bug report sent) but /myDataBase/data[B == "rabit"] which is a DbSet. The reason is when you don't use a primary key, then you can have more than one value in return, ie a set of values.
You can convert a dbset to an iter with DbSet.iterator. Then manipulate it with Iter: http://doc.opalang.org/module/stdlib.core.iter/Iter