Search code examples
node.jsmongodbmongoosemongoose-schema

Search for the presence of a string in multiple arrays of a document in mongo db


I wand to make a query in which I would provide a _id and country name now as a result I want to find the true or false value if the given country is present in these three arrays or not. If present then true instead false. For example I have country:France and _id:5e4d18bd10e5482eb623c6e4 then result will be-

country_array_1:true, country_array_2:true, country_array_3:false

I want a mongo db query for this type of input and output I can be aggregate or findOne but I want my answer

 0  _id:5e4d18bd10e5482eb623c6e4
       country_array_1:['France','Italy','China'],
       country_array_2:['Finland','England','France']
       country_array_3:['USA','turkey','India']

 1  _id:5e4345bd10e5482eb62E4X11f
       country_array_1:['Srilanka','Malaysia','Pakistan'],
       country_array_2:['Egypt','Austria','Netherland']
       country_array_3:['Mexico','turkey','India']

I want to make a query in which I would give input as

[Input]
 _id:5e4d18bd10e5482eb623c6e4,
 country:'France'

[Output]
 country_array_1:true,
 country_array_2:true,
 country_array_3:false

Solution

  • Aggregation pipeline

    db.test.aggregate([
      { $match: { _id: ObjectId("5e4d18bd10e5482eb623c6e4") } },
      {
        $project: {
          country_array_1: {
            $in: ["France", "$country_array_1"]
          },
          country_array_2: {
            $in: ["France", "$country_array_2"]
          },
          country_array_3: {
            $in: ["France", "$country_array_3"]
          }
        }
      }
    ]);
    

    Output:

    {
        "_id" : ObjectId("5e4d18bd10e5482eb623c6e4"),
        "country_array_1" : false,
        "country_array_2" : true,
        "country_array_3" : false
    }