Issue with passing a variable to the find_one query

Hi,
I’m using Python and I’m trying to do a compare in 2 collections to push any new changes or inserts to a 3rd collection.

I have a current collection and another collection that will be updated with new data. I want to see if there is any change of the new data when compared to the current collection and if so push it to a 3rd collection in order to push to an external system.

I searched and found some possible ideas but figured I’d just start with trying to pull data from the 2 collections based on one value. However, I’m getting stuck with the find_one query part. What I have so far:

>>>results=[]
>>> results.append(deptload.find_one())
>>>for item in results:
	deptid=item['DeptId']
	item2=deptprior.find_one({"Code":deptid})
	print(item2['Name'])

The issue is with the deptid in ‘({“Code”:deptid})’. It won’t accept the value from deptid and is returning back TypeError: ‘NoneType’ object is not subscriptable.

However when I print the deptid and pass it manually with the actual numbers, “12000”, it works just fine and brings back the name.

First am I on the right track to compare 2 collections and push the changes to a 3rd. And secondly, what am I doing wrong with the deptid variable?

Thanks.

I believe this issue is that find_one() returns None when no document matches the query. That means the results list in your example could end up being [None]. See:

To fix this, check if the return is None before appending to results:

doc = deptload.find_one()
if doc is not None:
    results.append(doc)

Also, if your application needs to track changes to a collection you may be interested in using change streams:

Thanks. For the ChangeStream it says I need a replica set. How do I install that?

Please enjoy https://docs.mongodb.com/manual/replication/.

The error is self-explanatory. You are trying to subscript an object which you think is a list or dict, but actually is None. This means that you tried to do:

None[something]

This error means that you attempted to index an object that doesn’t have that functionality. You might have noticed that the method sort() that only modify the list have no return value printed – they return the default None. ‘NoneType’ object is not subscriptable is the one thrown by python when you use the square bracket notation object[key] where an object doesn’t define the getitem method . This is a design principle for all mutable data structures in Python.