简体   繁体   中英

How to query multiple documents in mongodb with conditional params

I have message document with groupId and createdTS fields. and for query i have array of objects with groupId and lastVisit . I want to query all messages per groupId after lastVisit

I tried with $in with groupIds but it is not filtering createdTS with lastVisit

member schema

const GroupMemberSchema = new mongoose.Schema({
  userId: { type: String, required: true },
  groupId: { type: String, required: true },
  addTS: { type: Date, default: Date.now },
  lastVisit: { type: Date, default: Date.now }
});

Message Schema

const GroupMessageSchema = new mongoose.Schema({
  id: { type: String, required: true },
  groupId: { type: String, required: true },
  content: { type: String, required: true },
  createdTS: { type: Date, default: Date.now },
});

for query

GroupMessage.find({groupId: {$in: groupIds}})

If I understood the question correct then you need to fetch records that match each groupId and at the same time are greater than appropriate lastVisit . If to translate it to MongoDB query it would be something like this:

{
  "$or": [
    {
      "$and": [
        { "groupId": _groupId[i] }, 
        { "createdTS": { "$gt": _lastVisit[i] } } 
      ]
    },
    ...
  ]
}

Where _groupId[i] and _lastVisit[i] are array elements for list of groups and lastVisit timestamps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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