How to delete the last item of a collection in mongodb - python

I made a program with python and mongodb to do some diaries. Like this
Sometimes I want to delete the last sentence, just by typing "delete!"
But I dont know how to delete in a samrt way. I dont want to use "skip".
Is there a good way to do it?

Be it first or last item, MongoDB maintains unique _id key for each record and thus you can just pass that id field in your delete query either using deleteOne() or deleteMany(). Since only one record to delete you need to use deleteOne() like
db.collection_name.deleteOne({"_id": "1234"}) // replace 1234 with actual id

Related

How to use start_at() & end_at() in Firebase query with Python?

My Firebase realtime database schema:
Let's suppose above Firebase database schema.
I want to get data with order_by_key() which after first 5 and before first 10 not more. Range should be 5-10. Like in the image.
My key is always starting with -.
I'm trying this but failed. It returns 0. How can I do this?
snapshot = ref.child('tracks').order_by_key().start_at('-\5').end_at(u'-\10').get()
Firebase queries are based on cursor/anchor values, and not on offsets. This means that the start_at and end_at calls expect values of the thing you order on, so in your keys they expect the keys of those notes.
To get the slice you indicate you'll need:
ref.child('tracks').order_by_key().start_at('-MQJ7P').end_at(u'-MQJ8O').get()
If you don't know either of those values, you can't specify them and can only start from the first item or end on the last item.
The only exception is that you can specify a limit_to_first instead of end_at to get a number of items at the start of the slice:
ref.child('tracks').order_by_key().start_at('-MQJ7P').limit_to_first(5).get()
Alternatively if you know only the key of the last item, you can get the five items before that with:
ref.child('tracks').order_by_key().end_at('-MQJ8O').limit_to_last(5).get()
But you'll need to know at least one of the keys, typically because you've shown it as the last item on the previous page/first item on the next page.

dynamodb removing specific item from a list without collisions

I am using dynamodb with the python api, and have a list attribute, the list contains complex data in it.
I would like to be able to remove a specific item.
I found this tutorial explaining how to remove an item from the list by it's index.
And found this SO question regarding the situation.
Both the tutorial and the SO question show how to remove an item from a list by it's index, I have a more specific situation, where two users can use the same dynamodb table at once, and both of them might be trying to remove the same item, when using index, it can cause a situation as the following: having a list [1,2,3] two users want to remove the item "1" and using remove list[0], the first user removes the item 1, but now the list is [2,3] and the second user removes the item "2".
I found that you can remove a specific item by it's value when using dynamodb set datatype, but there is no set that can contain a complex data, only binary, str and number and I need to store something that is more like: {"att1":[1,2,3], "att2":str, "attr3":{...}} and nested.
How can I remove an item without the risk of removing another item by the index if someone already removed it before me causing me to remove the wrong item?
I don't remember exactly is dynamodb can return hash of the existing record
If not you can try to add it as additional field and create a key by this property
And then you can update your object with where clause
something like
aws dynamodb update-item \
--table-name ProductCatalog \
--key '{"myHash":{"N":"125948abcdef1234"}}' \
--update-expression
Idea is if object was already updated by someone hash also should be different

retain only specific rows psycopg2

I have a table containing jobs like this
id owner collaborator privilege
90 "919886297050" "919886212378" "read"
90 "919886297050" "919886297052" "read"
88 "919886297050" "919886212378" "read"
88 "919886297050" "919886297052" "read"
primary key is a composite of id, owner and collaborator
I want to pass in details of only the collaborators i want to retain. For example, if my collaborator = "919886212378" it means I want to delete the row for "919886297052" and keep the row for "919886212378"
Is there a way to do this in one query / execution instead of fetching the details separately and then performing the delete after filtering the missing values?
EDIT: My use case might have new collaborators added and old ones deleted. However, my input will just have a set of chosen collaborators so I will need to cross check with the old list, retain existing, add new and delete missing collaborators.
DELETE FROM table WHERE collaborator NOT IN ("919886212378", "id ..")
does the delete for the specific case you mentioned. But I don't know
how you get these id's. You give too little information regarding your exact case.
If you can get these id's by a query, you could make it a subquery like:
DELETE FROM table WHERE collaborator NOT IN (SELECT ... FROM ...)
Comparing the old and new collaborator lists in python kind of did the trick for me
original_list = ["C1","C2","C3","C4"] // result from query
updated_list= ["C1","C6","C7"] // list obtained from request
# compute the differences
to_be_added = set(updated_list).difference(set(original_list) )
to_be_deleted = set(original_list).difference(set(updated_list) )
Then I use an insert and delete statement within a transaction using the above two lists to make an update.

NDB query by keys value

New to using Python NDB.
I have something like:
class User(ndb.Model):
seen_list = nbd.KeyProperty(kind=Survey, repeated=True)
class Survey(ndb.Model):
same = ndb.StringProperty(required=True)
I want to be able to query for users that have not seen certain surveys.
What I am doing now is:
users = User.query(seen_list != 'survey name').fetch()
This does not work. What would be the proper way to do this? Should I first query the Survey list to get the key of the survey with a certain name? Is the != part correct?
I could not find any examples similar to this.
Thanks.
unfortunately, if your survey is a repeated property, it won't work that way. When you query a repeated property the datastore tries EVERY entry in your list, and if one works, it'll return the item. So when you say "!= survey name 1", if you have at least ONE entry in your list that isn't "survey name 1", it'll come back as positive, even if another result IS "survey name 1".
it's uninstinctive if you come from an SQL background I know.... the only way to go around that is to go programatically and evaluate the ones your query returns. It comes from the fact that, for repeated values, Big Table "flatten" your results, which means it creates one entry for EVERY value in your repeated attribute. so as it scans, it eventually finds one "correct" line with your info, grabs the object key from there, and returns the object.

Return the column names from an empty MySQL query result

I'm using Python 3.2.3, with the MySQL/Connector 1.0.7 module. Is there a way to return the column names, if the MySQL query returns an empty result?
For example. Say I have this query:
SELECT
`nickname` AS `team`,
`w` AS `won`,
`l` AS `lost`
WHERE `w`>'10'
Yet, if there's nobody over 10, it returns nothing, obviously. Now, I know I can check if the result is None, but, can I get MySQL to return the column name and a NULL value for it?
If you're curious, the reason I'm wondering if this is possible, is because I'm dynamically building dict's based on the column names. So, the above, would end up looking something like this if nobody was over 10...
[{'team':None,'won':None,'lost':None}]
And looks like this, if it found 3 teams over 10...
[{'team':'Tigers','won':14,'lost':6},
{'team':'Cardinals','won':12,'lost':8},
{'team':'Giants','won':15,'lost':4}]
If this kind of thing is possible, then I won't have to write a ton of exception checks all over the code in case of empty dict's all over the place.
You could use a DESC table_name first, you should get the column names in the first column
Also you already know the keys in the dict so you can construct yourself and then append things to it if the result has values.
[{'team':None,'won':None,'lost':None}]
But what I fail to see why you need this. If you have a list of dictionaries, I am guessing you will have for loop operations. For loop will not do anything to a empty list, so you would not have to bother about exception checks
If you have to do something like result[0]['team'] then you should definitely check if len(result)>0

Categories