Skip to content

Instantly share code, notes, and snippets.

@gatesvp
Created February 16, 2011 18:26
Show Gist options
  • Select an option

  • Save gatesvp/829863 to your computer and use it in GitHub Desktop.

Select an option

Save gatesvp/829863 to your computer and use it in GitHub Desktop.
Proper subset function for MongoDB $where clause
// Define function
subset = function (test, superset) {
if (test.length > superset.length) {
return false;
}
for (var i in test) {
found = false;
for (var j in superset) {
found = found || superset[j] == test[i];
}
if (!found) {
return false;
}
}
return true;
}
// Save function to the server, only needs to be done once.
db.system.js.save( { _id : "subset", value : subset } )
db.coll.find({ $where : "subset(this.attr, [2,3,4])" }) // subsets of 2,3,4
db.coll.find({ $where : "! subset(this.attr, [2,3,4])" }) // not subset of 2,3,4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment