rgio
rgio

Reputation: 11

Mongodb find all records where subfields in a given set in PHP

I have a Document that looks like this { "field1":"value1", "field2":{"unknown_key1":"value2", "unknown_key2":"value3", ... "unknown_keyN":"valueN"} }

and an array("arr1","arr2","arr3")

I want to query to find all documents where all of the unknown keys are in the set defined by my array, except the number N of these keys and their value is unknown. is this possible in Mongodb and if so how would I go about doing it.

Upvotes: 1

Views: 514

Answers (3)

anhlc
anhlc

Reputation: 14469

You can use $where in this case. If any of the unknown keys should be in the set defined by the array:

db.collection_name.find({$where: function() {
  var myarr = ["unknown_key", "arr1", "arr2", "arr3"];
  for(var key in this.field2) {
    var subkey = key.substr(0, key.length-1); //get unknown_key from unknown_keyN
    var id = myarr.indexOf(subkey); // check if in array 
    if (id != -1) return true;
  }
  return false;
}})

If all of the unknown keys should be in the set defined by the array:

db.collection_name.find({$where: function() {
  var myarr = ["unknown_key", "arr1", "arr2", "arr3"];
  if (this.field2  != undefined) {
    for(var key in this.field2) {
      var subkey = key.substr(0, key.length-1); //get unknown_key from unknown_keyN
      var id = myarr.indexOf(subkey); // check if in array 
      if (id == -1) return false;
    } 
    return true;
  } else {
    return false;
  }
}})

Upvotes: 0

Neo-coder
Neo-coder

Reputation: 7840

As per your questions I think some number of unknown_key presents in your array suppose if your array contains following values,

var values = ("arr1","arr2","arr3",..."unknown_key1","unknown_key2",.."arrN")

If it right then you should use following query to find out

for( i = 0; i < values.length ; i++ ) {
db.collectionName.find({},{"field2."+values[i]:1})
 } 

Upvotes: 1

Smarties89
Smarties89

Reputation: 561

I am not that familiar with PHP but what you normally do in other languages is using an array of objects and then use subnotation for this.

E.g:

"field1":"value1",
"field2":[
    {"unknown_key1":"value2"},
    {"unknown_key2":"value3"}
     ...
    {"unknown_keyN":"valueN"}
    ]

Then you can find them by

...find({"field2.unknown_key1": "value2", ... })

See another example here Mongo Query on Subfields

Upvotes: 0

Related Questions