Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

node.js - check an array of string value with array of object in mongodb

I have array of strings like this

let fromHour = ['2.5','3','3.5']
let toHour = ['2.5','3','3.5']

I have an array of object saved in mongoDB

timeRange = [
              {
                from:'2.5',
                to:'3'
              },
              {
                from:'3',
                to:'3.5'
               }

           ]

I want to check if any of my array of string value exist in that object value

I have tried this but it give me this error ( Unrecognized expression '$match' )

checkAppoint = await Appointment.aggregate([
                {
                  $project: {
                    date: myScheduleFinal[k].date,
                    status: { $in: ['pending', 'on-going'] },
                    timeRange: {
                      '$match': {
                        'from': { $in: fromHolder },
                        'to': { $in: toHolder },
                      },
                    },
                  },
                },
              ]);

also I have tried this solution and it work for me but it take to much time so I am trying this with aggregate

 checkAppoint = await Appointment.findOne({
                date: myScheduleFinal[k].date,
                status: { $in: ['pending', 'on-going'] },
                timeRange:{$elemMatch:{
                  from:{$in:fromHolder},
                  to:{$in:toHolder}
                }}
              });

So anyone have a solution for that

question from:https://stackoverflow.com/questions/65645161/check-an-array-of-string-value-with-array-of-object-in-mongodb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just try $elemMatch and $in operators,

  • using find() method
checkAppoint = await Appointment.find({
  timeRange: {
    $elemMatch: {
      from: { $in: fromHour },
      to: { $in: toHour }
    }
  }
})

Playground


  • using aggregate() method
checkAppoint = await Appointment.aggregate([
  {
    $match: {
      timeRange: {
        $elemMatch: {
          from: { $in: fromHour },
          to: { $in: toHour }
        }
      }
    }
  }
])

Playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...