Home > Blockchain >  Is there a way we can query using .find to take key as array of input
Is there a way we can query using .find to take key as array of input

Time:11-23

I want to provide array in filter of .find method
I found this method which matches a string in an array of input , Is there a way we can do It other way round .
db.collection.find({"phoneNumber.type": { $in: ["ACD", "BFG"] } })

CodePudding user response:

According to your comment where you are looking for something like: db.collection.find({ ['a','b','c'] : 'c' }) I think you can use this aggregate query:

  • First create an auxiliar field using $objectToArray to get keys as k field and value as v field.
  • Then $match using $in with keys. This $match return the documents where the key is in the array (in this case ["a", "b", "c"]) and value (v) is desired one. Also $elemMatch is used to ensure the object is the same.
  • And the last step is $project to remove the auxiliar field.
db.collection.aggregate([
  {
    "$addFields": {
      "aux": {"$objectToArray": "$$ROOT"}
    }
  },
  {
    "$match": {
      "aux": {
        "$elemMatch": {
          "k": {"$in": ["a","b","c"]},
          "v": "c"
        }
      }
    }
  },
  {
    "$project": {
      "aux": 0
    }
  }
])

Example here

CodePudding user response:

You could dynamically build an array of criteria on the client side:

const fieldnames = [ "field1","field2","field3" ];
const value = "match";
const criteria = fieldNames.map(function(fname){
    var ret = {};
    ret[fname] = value; 
    return ret;
});

Then if you want documents where any of them match, use:

Model.find({$or: criteria})

If you only want documwents were all of them match, use:

Model.find({$and: criteria})
  • Related