Mongodb 仅在存在时查询
Mongodb Query Only if Exist
let docs = {
chatid: 'userid1_userid2',
chats: [
{
from: 'user1',
to: 'user2',
message: 'Hii',
time: '2021-06-26T16:14:08.477+00:00'
},
{
from: 'user1',
to: 'user2',
message: 'Listen',
time: '2021-06-26T16:14:09.477+00:00',
deleted_by_userid1: '2021-06-26T16:14:10.477+00:00'
}
]
}
仅当字段 'deleted_by_userid1' 不存在时才获取 chatid 'userid1_userid2' 的最后一次聊天
您可以通过展开“聊天”数组字段并对没有“deleted_by_userid1”字段的文档进行排序,通过聚合执行以下操作,
db.collection.aggregate([
{"$unwind":"$chats"},
{"$match":{"chats.deleted_by_userid1":{$exists:false}}},
{"$sort":{"chats.time":-1}},
{"$limit":1}
])
let docs = {
chatid: 'userid1_userid2',
chats: [
{
from: 'user1',
to: 'user2',
message: 'Hii',
time: '2021-06-26T16:14:08.477+00:00'
},
{
from: 'user1',
to: 'user2',
message: 'Listen',
time: '2021-06-26T16:14:09.477+00:00',
deleted_by_userid1: '2021-06-26T16:14:10.477+00:00'
}
]
}
仅当字段 'deleted_by_userid1' 不存在时才获取 chatid 'userid1_userid2' 的最后一次聊天
您可以通过展开“聊天”数组字段并对没有“deleted_by_userid1”字段的文档进行排序,通过聚合执行以下操作,
db.collection.aggregate([
{"$unwind":"$chats"},
{"$match":{"chats.deleted_by_userid1":{$exists:false}}},
{"$sort":{"chats.time":-1}},
{"$limit":1}
])