mongodb - narrowing down mongo db query result -


so have mongo query:

{"r_rid" : "cr_448630" }  

which when execute find() returns

{      "_id" : { "$oid" : "soaifusladfjlasfjdkl2222"} ,      "mg" : 1 ,      "r_rid" : "cr_448630" ,      "users" : {          "5" : { "duration" : 15305 , "last_ts" : 99999999} ,          "33455" : { "duration" : 1563835 , "last_ts" : 1375826968} ,          "33606" : { "duration" : 4230245 , "last_ts" : 1375914301} ,          "33651" : { "duration" : 0 , "last_ts" : 1373305133}     } } 

what if want user index 33455

how go modifying mongo query

sorry, mongo n00b here...

i have few comments here, in general can not sub document out of document it's sole return value. best can straight out of mongodb johnnyhk writesis with:

db.test.find({"r_rid" : "cr_448630"}, {'users.33455': 1}) 

returns:

{   "_id": objectid("5202d6a2d3e4ab0f04cca6c2"),   "users": {     "33455": {       "duration": 1563835,       "last_ts": 1375826968     }   } } 

however, have make few comments schema. guideline, should not have value key. user id "33455" not key, can't predefine how many have , random names. makes difficult query index user_id example. can use numeric value, instead of string user id, again has better storage , indexing support. first suggestion change to:

{      "_id" : { "$oid" : "soaifusladfjlasfjdkl2222"} ,      "mg" : 1 ,      "r_rid" : "cr_448630" ,      "users" : [         { "userid" : 5, "duration" : 15305 , "last_ts" : 99999999},          { "userid": 33455, "duration" : 1563835 , "last_ts" : 1375826968},          { "userid": 33606, "duration" : 4230245 , "last_ts" : 1375914301},          { "userid": 33651, "duration" : 0 , "last_ts" : 1373305133}     ] } 

however, means db.test.find({"r_rid" : "cr_448630"}, {'users.33455': 1}) no longer works.

so second suggestion change document above multiple documents, this:

{      "userid" : 5, "duration" : 15305 , "last_ts" : 99999999     "mg" : 1 , "r_rid" : "cr_448630" ,  }, {      "userid": 33455, "duration" : 1563835 , "last_ts" : 1375826968      "mg" : 1 , "r_rid" : "cr_448630" ,  }, {      "userid": 33606, "duration" : 4230245 , "last_ts" : 1375914301     "mg" : 1 , "r_rid" : "cr_448630" ,  }, {      "userid": 33651, "duration" : 0 , "last_ts" : 1373305133     "mg" : 1 , "r_rid" : "cr_448630" ,  } 

as can see, i've duplicated mg , r_rid each user document. schema provides easier querying, , can make use of index query r_rid user_id @ same time:

db.test.ensureindex( { r_rid: 1, userid: 1 } ); db.test.find( { 'r_rid': "cr_448630", 'userid' : 33455 } ); 

Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -