简体   繁体   English

Mongodb查找PHP中给定集中子字段的所有记录

[英]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"} } 我有一个看起来像这样的文档{ "field1":"value1", "field2":{"unknown_key1":"value2", "unknown_key2":"value3", ... "unknown_keyN":"valueN"} }

and an array("arr1","arr2","arr3") 和一个数组(“ 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. 我想查询查找所有文档,其中所有未知键都在我的数组定义的集合中,除了这些键的数量N和其值未知之外。 is this possible in Mongodb and if so how would I go about doing it. 在Mongodb中这可能吗?如果可以,我将如何去做。

As per your questions I think some number of unknown_key presents in your array suppose if your array contains following values, 根据您的问题,我认为您的数组中存在一些unknown_key,如果您的数组包含以下值,

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. 我对PHP不太熟悉,但是您通常用其他语言执行的操作是使用对象数组,然后为此使用子符号。

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 在此处查看另一个示例, 在子字段上进行Mongo查询

You can use $where in this case. 在这种情况下,您可以使用$where 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;
  }
}})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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