Syntax error in db.collection.save() - mongodb

I am trying MongoDB for first time but I am stuck on the following syntax error: unexpected token illegal. I checked it and it looks OK. I found similar a problem on StackOverflow but that is for a different error. What am I doing wrong?
Here is my script:
db.student.save({"_id":ObjectId(5983548781331adf45ec7),"name":"replaced","age":55})

The problem is here : ObjectId(5983548781331adf45ec7)
ObjectId accepts a string of 24 hex digits.
ObjectId("<24 hex digits here>")
E.g. ObjectId("0123456789abcdef01234567")

If you are using a backend source code such as groovy (with Grails GORM), you can try the following script which is very clean and readable:
def studentFromDB = db.student.findById("5983548781331adf45ec7")
studentFromDB.name = "replaced"
studentFromDB.age = 55
studentFromDB.save(flush: true, failOnError: true)
If you use it directly onto the mongo you should use the MongoDB update, for example:
db.student.update(
{"_id":ObjectId(5983548781331adf45ec7) },
{
name: "replaced",
age: 55
},
{ upsert: true }
)

I fixed it...the error is i missed quotes inside 'ObjectId'
the corrected script is `db.student.save({"_id":ObjectId("57fcf46763ecce707f071884"),"name":"rep_dsave","age":37}).
Thanks 4J41 and rotemy
`

Related

Pyspark how to remove punctuation marks and make lowercase letters in Rdd?

I would like to remove punctuation mark and make the lowercase letters in RDD?
Below is my data set
l=sc.parallelize(["How are you","Hello\ then% you"\
,"I think he's fine+ COMING"])
I tried below function but I got an error message
punc='!"#$%&\'()*+,-./:;<=>?#[\\]^_`{|}~'
def lower_clean_str(x):
lowercased_str = x.lower()
clean_str = lowercased_str.translate(punc)
return clean_str
one_RDD = l.flatMap(lambda x: lower_clean_str(x).split())
one_RDD.collect()
But this gives me an error. What might be the problem? How can I fix this?
Thank you.
You are using the python translate function in a wrong way.
As I am not sure if you are using python 2.7 or python 3, I am suggesting an alternate approach.
The translate function changes a bit in python 3.
The following code will work irrespective of the python version.
def lower_clean_str(x):
punc='!"#$%&\'()*+,-./:;<=>?#[\\]^_`{|}~'
lowercased_str = x.lower()
for ch in punc:
lowercased_str = lowercased_str.replace(ch, '')
return lowercased_str
l=sc.parallelize(["How are you","Hello\ then% you","I think he's fine+ COMING"])
one_RDD = l.map(lower_clean_str)
one_RDD.collect()
Output :
['how are you', 'hello then you', 'i think hes fine coming']

How to Define and Use Variables in Pymongo Aggregation Script

I am trying to learn about mongodb aggregation. I've been able to get the commands to work for a single output. I am now working on a pymongo script to parse through a dirty collection and output sterilised data into a clean collection. I am stuck on how to define variables properly so that I can use them in the aggregation command. Please forgive me if this turns out to be a trivial matter. But I've been searching through online documents for a while now, but I've not had any luck.
This is the script so far:
from pymongo import MongoClient
import os, glob, json
#
var_Ticker = "corn"
var_Instrument = "Instrument"
var_Date = "Date"
var_OpenPrice = "prices.openPrice.bid"
var_HighPrice = "prices.highPrice.bid"
var_LowPrice = "prices.lowPrice.bid"
var_ClosePrice = "prices.closePrice.bid"
var_Volume = "prices.lastTradedVolume"
var_Unwind = "$prices"
#
#
client = MongoClient()
db = client.cmdty
col_clean = var_Ticker + "_clean"
col_dirty = var_Ticker + "_dirty"
db[col_dirty].aggregate([{$project:{_id:0,var_Instrument:1,var_Date:1,var_OpenPrice:1,var_HighPrice:1,var_LowPrice:1,var_ClosePrice:1,var_Volume:1}},{$unwind:var_Unwind},{$out:col_clean}])
This is the error that I get:
>>> db[col_dirty].aggregate([{$project:{_id:0,var_Instrument:1,var_Date:1,var_OpenPrice:1,var_HighPrice:1,var_LowPrice:1,var_ClosePrice:1,var_Volume:1}},{$unwind:var_Unwind},{$out:col_clean}])
File "<stdin>", line 1
db[col_dirty].aggregate([{$project:{_id:0,var_Instrument:1,var_Date:1,var_OpenPrice:1,var_HighPrice:1,var_LowPrice:1,var_ClosePrice:1,var_Volume:1}},{$unwind:var_Unwind},{$out:col_clean}])
^
SyntaxError: invalid syntax
If I take out the variables and use the proper values, the command works fine.
Any assistance would be greatly appreciated.
In Python you must wrap a literal string like "$project" in quotes:
db[col_dirty].aggregate([{"$project":{"_id":0,var_Instrument:1 ...
The same goes for "_id", which is a literal string. This is different from how Javascript treats dictionary keys.
Note that you should not put quotes around var_Instrument, since that is not a string literal, it's a variable whose value is a string.

Play! + Scala: Split string by commnas then Foreach loop

I have a long string similar to this:
"tag1, tag2, tag3, tag4"
Now in my play template I would like to create a foreach loop like this:
#posts.foreach { post =>
#for(tag <- #post.tags.split(",")) {
<span>#tag</span>
}
}
With this, I'm getting this error: ')' expected but '}' found.
I switched ) for a } & it just throws back more errors.
How would I do this in Play! using Scala?
Thx in advance
With the help of #Xyzk, here's the answer: stackoverflow.com/questions/13860227/split-string-assignment
Posting this because the answer marked correct isn't necessarily true, as pointed out in my comment. There are only two things wrong with the original code. One, the foreach returns Unit, so it has no output. The code should actually run, but nothing would get printed to the page. Two, you don't need the magic # symbol within #for(...).
This will work:
#for(post <- posts)
#for(tag <- post.tags.split(",")) {
<span>#tag</span>
}
}
There is in fact nothing wrong with using other functions in play templates.
This should be the problem
#for(tag <- post.tags.split(",")) {
<span>#tag</span>
}

Collection.update giving server error

Trying to learn the Meteor framework as well as coffeescript/node all at once. Been working on a simple file upload program that utilizes onloadend. When the FileReader onloadend event function is called I try to determine if the file already exists and if so I update with the new file data and version.
The code works for insert but not update. Can someone help? I've posted to meteor-talk w/o an answer as I suspect its the weekend (when I do most of my experimentation).
Code snippet...
file_reader.onloadend = ((file_event) ->
(event) ->
f_filename = escape file_event.name
version = 0
f_record = null
f_record = doc_repo.findOne { name: f_filename }
if f_record && f_record.name
doc_repo.update
name: f_filename
,
$set:
version: 10
else
doc_repo.insert
name: f_filename
data: event.target.result
version: 0
)(file_obj)
Error
Exception while invoking method '/documents/update' TypeError: Cannot read property 'toBSON' of undefined
at Function.calculateObjectSize (/usr/local/meteor/lib/node_modules/mongodb/node_modules/bson/lib/bson/bson.js:210:12)
at BSON.calculateObjectSize (/usr/local/meteor/lib/node_modules/mongodb/node_modules/bson/lib/bson/bson.js:1463:15)
at UpdateCommand.toBinary (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/commands/update_command.js:67:20)
at Connection.write (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/connection/connection.js:138:40)
at __executeInsertCommand (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/db.js:1837:14)
at Db._executeInsertCommand (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/db.js:1912:7)
at Collection.update (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/collection.js:445:13)
at app/packages/mongo-livedata/mongo_driver.js:178:16
at Db.collection (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/db.js:507:44)
at _Mongo._withCollection (app/packages/mongo-livedata/mongo_driver.js:51:13)
It looks like Mongo is not getting the second parameter which it needs to do the update. So in regular JavaScript it's expecting this:
collection.update({..selector..}, { .. modifier });
So I'd try putting some curly brackets around the modifier object, like this:
doc_repo.update
name: f_filename,
{
$set:
version: 10
}

CoffeeScript parse error - Unexpected "(" - But there's no "(" in the code

Here's the original code:
res.write JSON.stringify {"#{result.statusCode}": "OK"}
and here's the error that both the CoffeeScript linter in SublimeText 2 and the "Try CoffeeScript" interpreter on the CoffeeScript site give me:
PARSE ERROR ON LINE 1: UNEXPECTED '('
Obviously there's no open parens in the code, so I don't understand the error. Is it a bug in the CoffeeScript parser?
The smallest line of code that does this seems to be something like this:
{"#{a}": ""}
I'm assuming that string interpolation in an object's key is valid, but I don't know for sure.
EDIT:
After some investigation it seems that it's not valid to do the string interpolation in the key because the resulting JavaScript would be invalid.
This:
{"#{a}": "stuff}
would translate to something like:
{ "" + a: "stuff"}
which isn't valid.
But can someone explain why the error message it gives me is so wrong?
I'm assuming that string interpolation in an object's key is valid, but I don't know for sure.
Unfortunately it's not.
You'll have to do something like
(json = {})[result.statusCode] = 'OK'
res.write JSON.stringify json
or if you want a one-liner
res.write (-> ((json = {})[result.statusCode] = 'OK') and JSON.stringify json)()
As for the misleading error, CoffeeScript is trying to translate your {"#{a}": ''} into {("" + a): ""} which is not valid JavaScript. CoffeeScript is throwing the error at that left paren.