Home > OS >  finds records in a collection that contains all values in a given array
finds records in a collection that contains all values in a given array

Time:01-11

is there a function in mongodb that finds records in a collection that contains all values in a given array? ex: i have a collection called channels, the collection has a field called fields. The field fields contains an array of objects. example:

{
  _id: "1advs23rfwdfsd23r32r2wf89UJ*ADJ8j10u9u1-2u3",
  fields:[
     {
      "field_name": "first_name"
     },
     {
      "field_name": "last_name"
     },
    ]
 }

is there a function that can find all the Channels that contain a certain set of fields? example: find all the channels that contain the fields :"first_name", "last_name", "state".

I tried the following but it didnt work

Channel.find({ fields: { $all: [{ "field_name": "state" },{ "field_name": "last_name" },{ "field_name": "first_name" }] } })

CodePudding user response:

Use $in

It is used to select documents in which the field's value equals any of the given values in the array

and $all will work only if all the values match the values of an array field in a document

Channel.find({ fields: { $in: [{ "field_name": "state" },{ "field_name": "last_name" },{ "field_name": "first_name" }] } })

  • Related