Query an array of embedded documents in mongodb -


i'm having little trouble writing query needs compare given value against field in all embedded documents within array. give example make issue less abstract.

let's want use mongodb store last queries users on network have entered different online search engines. entry in collection have structure :

{     '_id' : 'zinfandel',      'last_search' : [         {             'engine' : 'google.com',             'query' : 'why sky blue'          },         {             'engine' : 'bing.com',              'query' : 'what love'         },         {   'engine' : 'yahoo.com',             'query' : 'how tie tie'         }     ] } 

now let's user username enters new query engine. code stores query in db needs find out whether there exists entry engine user used. if yes, entry updated new query. if not, new entry should created. idea $push if there no entry given engine , $set otherwise. purpose, tried write push :

db.mycollection.update(     { '_id' : username , search.$.engine : { '$ne' : engine } },     { '$push' : { 'search.$.engine' : engine, 'search.$.query' : query } } )  

however, pushes new embedded document if there entry given engine. problem seems $ne operator doesn't work arrays expect work. need way make sure not single embedded document in array has "engine" entry matches specified engine.

does have idea how that? please tell me if need further clarify question ...

you can push item array following command:

db.mycollection.update({     _id: "zinfandel",      "last_search.engine": {         $nin: ["notwellknownengine.com"]     } }, {     $push: {         "last_search": {             "engine" : "notwellknownengine.com",              "query" : "stackoveflow.com"         }     } }); 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -