in user_history collection
user_name: john
eat : [{food:'apple', timestamp:123}, {food:'cheese', timestamp:80}]
user_name: paul
eat : [{food:'melon', timestamp:125}, {food:'bread', timestamp:60}]
user_name: mattew
eat : [{food:'water', timestamp:90}, {food:'pizza', timestamp:91}]
I need to get food which has timestamp over 100
my code:
db.user_history.find({"eat.timestamp":{$gte:100}},{"eat.food":1})
result:
{'_id': ObjectId('......'),'eat':[{food:'apple'},{food:'cheeza'}]},
{'_id': ObjectId('......'),'eat':[{food:'melon'},{food:'bread'}]}
result I want to get:
{'_id': ObjectId('......'), 'eat':{food:apple}},
{'_id': ObjectId('......'), 'eat':{food:melon}}
how could I get this?
I dont think its possible,see the ticket: https://jira.mongodb.org/browse/SERVER-828.
Looks like this question is already asked
Related
I want to mock mongo in order to make some unit test with unittest for Flask. The doc about this is so huge and I don't really understand how to make it.
I want to test a POST method with the following data:
from unittest import TestCase, main as unittest_main, mock
from bson.objectid import ObjectId
from app import app
sample_user = {
'Id': ObjectId('5d55cffc4a3d4031f42827a3'),
'Username': 'LeTest',
'Mail': 'sendme#gmail.com',
'password': 'test123',
'Qrcode': 'TODO'
}
Can you explain me how I can test if the sample_user where added to my mongo collection ?
Thx !
I found the answer:
Here you have my code in order to mock mongoDB Data with Flask
def test_post_food(self):
# Mock the food value in ./api.food.py
with unittest.mock.patch('api.food.food') as MockFood:
# Force the return value of food.insert_one(json) to sample_food
MockFood.insert_one.return_value = sample_food
with self.client.post("/api/addFood", json=sample_food[0]) as res:
# Check if food.insert_one(json) was called
MockFood.insert_one.assert_called()
self.assertEqual(res.status_code, 200)
self.assertEqual(res.data, b'{"Response":"Food was added"}\n')
sample_food = [{
"_id": {
"$oid": "619e8f45ee462d6d876bbdbc"
},
'Utilisateur': "999",
'Nom': 'Danette Vanille',
'Marque': 'Danone',
'Quantite': 4,
'ingredients': [
'lait entier',
'lait écrémé reconstitué à base de lait en poudre',
'sucre',
'crème',
'lait écrémé concentré ou en poudre',
'épaississants (amidon modifié, carraghénanes)',
'perméat de petit lait (lactosérum) en poudre',
'amidon',
'arôme (lait)',
'colorant (bêta-carotène)'
],
'Date': '20/12/2021',
'Valeurs': {
'Energie': '107 kcal',
'Matières grasses': '3,0g',
'Glucides': '17,1g',
'Proteines': '3g',
'Sel': '0,14g'
},
'Poids': '125g',
'Lieu': 'Frigo',
'Category': "Produit laitiers"
}]
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}}])
I'm looking for a sample code using SoftLayer_Virtual_Guest::setTransientWebhook for Transient VSI. Is there a sample code?
Thanks
Behzad
Try with next requests:
Method GET
http://api.softlayer.com/rest/v3.1/SoftLayer_Account/getVirtualGuests?objectMask=mask[id,transientGuestFlag]&objectFilter={"virtualGuests":{"transientGuestFlag":{"operation": 1}}}
Data 1 means true also 0 means false, in this case, we use one with data 1
Choose the VSI id you want to set and use the following request:
Method POST
http://api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest/111111/setTransientWebhook
Body
{"parameters":[
"https://test1.com",
"testsupport"]
}
The 111111 data is the VSI that we chose in the previous request.
Reference
https://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest/#transientGuestFlag
https://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/setTransientWebhook/
I hope it helps you
Thanks Daniel, would this be equivalent code in python: request = client['Virtual_Guest'].createObject({
'hostname': hostname,
'domain': domainname,
'startCpus': cpus,
'maxMemory': memory,
'hourlyBillingFlag': 'true',
'datacenter': {'name': 'tor01'},
'operatingSystemReferenceCode': os_code,
# 'localDiskFlag': 'false',
"supplementalCreateObjectOptions": {"flavorKeyName": "C1_1X1X25"},
'transientGuestFlag': 'true',
# 'sshKeys': [{"id":201867}]
"parameters":["https://test1.com","testsupport"].
What am I missing here? I simply copy paste the example on https://github.com/ankane/searchkick to the console and I get an error.
2.2.2 :001 > User.search "jim", boost_by_distance: {field: :location, origin: {lat: 37, lon: -122}}
NoMethodError: undefined method `reverse' for {:lat=>37, :lon=>-122}:Hash
Try upgrading to the latest version of Searchkick (1.1.1).
I was trying to sort the results by distance. Ended up using this query instead:
order: {_geo_distance: {coordinates: "#{find_coordinates[1]},#{find_coordinates[0]}", order: "asc", unit: "mi"} }
While I grab the coordinates from the ip with Geocoder:
def find_coordinates
Geocoder.coordinates(request.remote_ip)
end
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.