型号:
const Room = new Schema({
topic: String,
messages: [{
text: String,
readByUsers: [String] // Array of users Ids, which read this message
}]
});
示例数据:
{
topic: 'First',
messages: [
{
text: 'First message',
readByUsers: ['id1', 'id3', 'id2']
},
{
text: 'Second message',
readByUsers: ['id1', 'id2'] //id3 not read this
}
]
},
{
topic: 'Second',
messages: [
{
text: 'Third message',
readByUsers: ['id1', 'id3', 'id2']
},
{
text: 'Fourth message',
readByUsers: ['id1', 'id2', 'id3']
}
]
}
我的目标 - 接收第一个对象,因为 id3 用户未读取第二条消息(此密钥在readByUsers数组中不存在)
查询如下: 搜索所有文档,其中一些 messages.readByUsers 不包含特定的userId
Model.find(messages.readByUsers: {$nin: [userId]})
仅当 messages.readByUsers 中没有人包含id时才有效
Model.find(messages.readByUsers: {$nin: ['id4']})
- 返回两个对象
答案 0 :(得分:3)
您可以使用$elemMatch
运算符来查找至少一个满足其条件的元素:
Model.find({messages: {$elemMatch: {readByUsers: {$ne: 'id3'}}}})