PyMongo : Array filtered positional operator update gives me error - mongodb

I am trying to run a python code to update a collection with arrays. The below statement give error wtih pymongo . Please guide
db.students.update({}, {'$set': {"grades.$[element]": 100}}, {'multi': true, 'arrayFilters': [{"element": { '$gte': 100}}]} )
tried : multi=True tried : multi:True
I am getting the below error :
common.validate_boolean("upsert", upsert)
File "F:\Program Files\Python3.7\lib\site-packages\pymongo\common.py", line 159, in validate_boolean
raise TypeError("%s must be True or False" % (option,))
TypeError: upsert must be True or False

Pymongo's syntax is a tad different than Mongo's syntax, you should write it like this:
db.students.update({}, {'$set': {"grades.$[element]": 100}}, multi=True, array_filters=[{"element": {'$gte': 100}}])
Also update is deprecated, and in your case you should use update_many instead.
db.students.update_many({}, {'$set': {"grades.$[element]": 100}}, array_filters=[{"element": {'$gte': 100}}])

Related

logstash-input-mongodb loop on a "restarting error" - Timestamp

I try to use the mongodb plugin as input for logstash.
Here is my simple configuration:
input {
mongodb {
uri => 'mongodb://localhost:27017/testDB'
placeholder_db_dir => '/Users/TEST/Documents/WORK/ELK_Stack/LogStash/data/'
collection => 'logCollection_ALL'
batch_size => 50
}
}
filter {}
output { stdout {} }
But I'm facing a "loop issue" probably due to a field "timestamp" but I don't know what to do.
[2018-04-25T12:01:35,998][WARN ][logstash.inputs.mongodb ] MongoDB Input threw an exception, restarting {:exception=>#TypeError: wrong argument type String (expected LogStash::Timestamp)>}
With also a DEBUG log:
[2018-04-25T12:01:34.893000 #2900] DEBUG -- : MONGODB | QUERY | namespace=testDB.logCollection_ALL selector={:_id=>{:$gt=>BSON::ObjectId('5ae04f5917e7979b0a000001')}} flags=[:slave_ok] limit=50 skip=0 project=nil |
runtime: 39.0000ms
How can I parametrize my logstash config to get my output in the stdout console ?
It's because of field #timestamp that has ISODate data type.
You must remove this field from all documents.
db.getCollection('collection1').update({}, {$unset: {"#timestamp": 1}}, {multi: true})

Meteor MongoDB Error

I have this issue with my meteor app. When I run this query on my chrome console, It returns the expected data
Questions.find({}, {sort:{commentLength: -1}})
but when I run it in the console as db.questions.find({}, {sort:{commentLength: -1}})
it returns this error
error: {
"$err" : "Can't canonicalize query: BadValue Unsupported projection option: sort: { commentLength: -1.0 }",
"code" : 17287
}
Why does this error happen? Thanks
sort has a different syntax when executed in a mongodb shell. Try this instead:
db.questions.find().sort({commentLength: -1})

Why pymongo eval result is different from mongo shell?

When I execute "db.abc.find()" in mongo shell it returns the following answer:
db.abc.find()
{ "_id" : ObjectId("56a942bfec926681f17f09b6"), "name" : "foo" }
But when I execute the same command via PyMongo's eval method I receive a different answer:
>>> from pymongo import MongoClient
>>> client = MongoClient()
>>> db = client.test
>>> db.eval('db.abc.find()')
{u'_special': False, u'_options': 0.0, u'_ns': u'test.abc', u'_db': {u'_mongo': {u'slaveOk': False, u'host': u'EMBEDDED'}, u'_name': u'test'}, u'_skip': 0.0, u'_numReturned': 0.0, u'_query': {}, u'_limit': 0.0, u'_mongo': {u'slaveOk': False, u'host': u'EMBEDDED'}, u'_collection': {u'_shortName': u'abc', u'_db': {u'_mongo': {u'slaveOk': False, u'host': u'EMBEDDED'}, u'_name': u'test'}, u'_mongo': {u'slaveOk': False, u'host': u'EMBEDDED'}, u'_fullName': u'test.abc'}, u'_cursor': None, u'_fields': None, u'_batchSize': 0.0}
What this is happening?
How to fix it?
Well, eval() is definitely evil and is actually deprecated.
You should wrap the code into a function to make it work:
from bson import Code
db.eval(Code('function () { return db.abc.find(); }'))
Why don’t you just call db.abc.find() from Python and get you document(s) from cursor?
[doc for doc in db.abc.find()]
Or still:
db.abc.find_one()

MongoDB :error doing update (anon):1552 on Update command

I am using MongoDB Version of 1.2.6
I was doing a multiple update on a collection ( If a field named yesterday exists ,update it or else create field called yesterday for that record )
This is my query
db.userLoginCount.update({yesterday : {$exists : false}}, {$set: {yesterday : '07082013'}},false,true)
Once i run this , i am getting an error as
Tue Jul 9 02:43:05 Error: error doing update (anon):1552
Please tell me what is wring with the above query ??

Append key value if mongodb collection does not have the value?

I have a db with a bunch of collections.
Some of them have 'status' and some don't.
How can I insert 'status':'pending' into the collections that lack 'status' - but not overwrite the collections that already have a status?
Using pymongo / flask / python 2.7
I tried this:
orders = monDB.find('order')
for order in orders:
if not order['status']:
monDB.update('order', {'status':'pending'})
print 'success'
But nothing happens. What am I doing wrong?
Use $exists to check if the field exists and $set to create it if it doesn't. Assuming monDB is your collection:
monDB.update({'status': {'$exists' : False}}, {'$set' : {'status': 'pending'}}, multi=True)
In the mongo shell:
> db.myQueue.update({status: {$exists: false}}, {$set : {status: 'pending'}}, false, true)
See http://docs.mongodb.org/manual/reference/operators/ and http://docs.mongodb.org/manual/applications/update/#crud-update-update.