MongoDB: request for a key that has a place in its name

I want to get the values โ€‹โ€‹of only certain keys from the MongoDB collection.

But there are several keys in the collection that have a โ€œspaceโ€ in their name, for example:

"Parent":{"key1": //some string, "key2": //some string, "key 3": //some string} 

I know this is the wrong approach, because ideally there should be no spaces in the key name, but nevertheless, how can I request this key? I am using Python and PyMongo.

For regular keys, I can do this:

 db.coll_name.find({"key": "India"}, {"_id": 0, "Parent.key1": 1, "Parent.key2": 1}) 

So, how can I use the key "Parent ['key 3']" in the second argument of the above request? Is there any way to achieve this?

Here's a query that returns data (works):

 db.coll_name.find({}, {"Parent.key1": 1, "_id": 0}) 

Here is a query that does not return data:

 db.coll_name.find({}, {"Parent['key 3']": 1, "_id": 0}) 
+6
source share
2 answers

Well, the only way you could build this is:

 content = {}; content["Parent"] = {} content["Parent"]["key2"] = 1 content["Parent"]["key 3"] = 1 db.coll_name.insert(content) 

But you seem to be missing that there is nothing wrong with that:

 db.coll_name.find({ "Parent.key 3": 1} ) 

Or in projection

  db.coll_name.find({}, { "Parent.key 3": 1 }) 

This is "dot notation" , not object notation, and as long as you specify the key names (which is mandatory for dot notation), then all this is fine, and you may have free space.

+7
source

I know this is the wrong approach, because ideally there should be no spaces in the key name, but nevertheless, how can I request this key?

I suggest:

  • Remove space from document key with bulk write operations

     bulk = coll_name.initialize_unordered_bulk_op() count = 1000 for doc in coll_name.find(): parent = {} parent.setdefault('Parent', {}) for key, val in doc['Parent'].items(): parent['Parent'][key.replace(' ', '')] = val bulk.find({'_id': doc['_id']}).update({'$set': parent}) count += 1 if count % 1000 == 0: # Execute per 1000 operations and re-init. bulk.execute() bulk = coll_name.initialize_unordered_bulk_op() # Clean up queues if count % 1000 != 0: bulk.execute() 
  • Then your projection will be easier

     db.coll_name.find({'key': 'India'}, {'_id': 0, 'Parent.key1': 1, 'Parent.key2': 1, 'Parent.key3': 1 }) 
+1
source

All Articles