Showing posts with label Mongodb. Show all posts
Showing posts with label Mongodb. Show all posts

Thursday, March 5, 2015

Get the list of name of fields in mongo using pymongo and mongodb shell

followings will list all fields exist in a collection in mongodb :

Pymongo: 

#Using pymongo and connection named 'db'

reduce(
    lambda all_keys, rec_keys: all_keys | set(rec_keys), 
    map(lambda d: d.keys(), db.things.find()), 
    set()
)

Mongodb Shell:

mr = db.runCommand(
{"mapreduce" : "temp",  
"map" : function() { for (var key in this) { emit(key, null); } }, "reduce" : function(key, stuff) { return null; }, "out": "temp" + "_keys" }) 
db[mr.result].distinct("_id")




Wednesday, February 18, 2015

How to change data type of a field in mongo

Following query helps you convert the data type of a field from

  • string to integer:

db.my_collection.find().forEach( function(obj) {
    obj.field-name= parseInt(obj.field-name);
    db.my_collection.save(obj);

});


  • and from integer to string : 

db.my_collection.find().forEach( function(obj) {
    obj.field-name= ""+obj.field-name;
    db.my_collection.save(obj);

});

Tuesday, January 27, 2015

How to autoincrement id at every insert in Pymongo?

Use a separate counters collection to track the last number sequence used. The _id field contains the sequence name and the seq field contains the last value of the sequence.

1- Insert into the counters collection, the initial value for the userid:
 db.orgid_counter.insert({'_id': "userid", 'seq': 0})  

2- Create a getNextSequence function in target language(I am using python) that accepts a name of the sequence. The function uses the find_And_Modify() method to atomically increment the seq value and return the new value:
 def getNextSequence(collection,name):  
   return collection.find_and_modify(query= { '_id': name },update= { '$inc': {'seq': 1}}, new=True ).get('seq');  

3-Use this getNextSequence() function during insert() and insert new user with new generated id .


  db.users.insert({'_uid': getNextSequence(db.orgid_counter,"userid"), 'name': "Sara a"})  

You can verify the results with find():
 db.users.find()