简体   繁体   English

如何使用条件参数在mongodb中查询多个文档

[英]How to query multiple documents in mongodb with conditional params

I have message document with groupId and createdTS fields. 我有带有groupIdcreatedTS字段的消息文档。 and for query i have array of objects with groupId and lastVisit . 对于查询,我有具有groupIdlastVisit的对象数组。 I want to query all messages per groupId after lastVisit 我想查询lastVisit之后每个groupId所有消息

I tried with $in with groupIds but it is not filtering createdTS with lastVisit 我试着用$in同组id,但它没有过滤createdTSlastVisit

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 . 如果我理解正确的问题,那么您需要获取与每个groupId匹配的记录,并且同时大于适当的lastVisit If to translate it to MongoDB query it would be something like this: 如果将其转换为MongoDB查询,将是这样的:

{
  "$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. 其中_groupId[i]_lastVisit[i]是组列表和lastVisit时间戳的数组元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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