简体   繁体   中英

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.

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})
 } 

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.

Eg:

"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

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;
  }
}})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM