[英]MongoDB Nested Documents Aggregation using Change Events
問題是當我在數組字段中推送一個新文檔時,它變成了一個點符號。
我想要實現的是過濾更改事件或 Collection.watch() 的響應。
但這會發生
我無法訪問 updateDescription.updatedFields.message 因為它變成了點符號。
我試着用
var filter = [{
$match: {
$and: [
{ 'documentKey._id': req.body.id },
{'updateDescription.updatedFields.message': // value of current length of the messages array}
]
}
}];
和
var filter = [{
$match: {
$and: [
{ 'documentKey._id': req.body.id },
{'updateDescription.updatedFields.messages' : {$exists: true}}
]
}
}];
我還使用了投影:
try{
res.status(200).set({
"connection":"keep-alive",
"cache-control": "no-cache",
"content-type":"application/json"
});
var query = await User.findOne({'_id': req.body.id});
var len = parseInt(query['messages'].length);
var _str = 'messages.'+String(len);
console.log(_str)
var project = [{$project: {'updateDescription.updatedFields' : {$objectToArray: '$updateDescription.updatedFields'}}}]
var filter = [{
$match: {
$and: [
{ 'documentKey._id': req.body.id },
{'updateDescription.updatedFields.k': _str}
]
}
}];
await User.watch(filter, project).on('change', data => console.log(data))
}catch(err){
res.status(500).send(err);
}
但我仍然沒有任何解決方案如何解決這個問題。
問題是你投射錯了。
$project: {'updateDescription.updatedFields' : {$objectToArray: '$updateDescription.updatedFields'}}
應該是
{$project: { 'updateDescription.updatedFields' : {$objectToArray: '$updateDescription.updatedFields'}, 'documentKey._id': req.body.id }}
然后你 go 在 $match 上使用正則表達式
{$match: {
$and: [
{ 'documentKey._id': req.body.id },
{'updateDescription.updatedFields.k': {$regex:"^matches"}}
]}
這是完整的工作片段:
try{
res.status(200).set({
"connection":"keep-alive",
"cache-control": "no-cache",
"content-type":"application/json"
});
var filter = [
{$project: { 'updateDescription.updatedFields' : {$objectToArray: '$updateDescription.updatedFields'}, 'documentKey._id': req.body.id }},
{$match: {
$and: [
{ 'documentKey._id': req.body.id },
{'updateDescription.updatedFields.k': {$regex:"^matches"}}
]
}
}];
await User.watch(filter).on('change', data => console.log(data.updateDescription.updatedFields))
}catch(err){
res.status(500).send(err);
}
它不匹配的原因是因為您使用的是 $and 運算符並且沒有“documentKey._id”可以匹配,因為您將其投影錯誤。
$filter
和$project
階段應該放在一個數組中。 watch
function 采用(管道陣列,選項對象)。 嘗試:
var filter = [
{$project: {'updateDescription.updatedFields' : {$objectToArray: '$updateDescription.updatedFields'}}},
{$match: {
$and: [
{ 'documentKey._id': req.body.id },
{'updateDescription.updatedFields.k': _str}
]
}
}];
await User.watch(filter).on('change', data => console.log(data))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.