问题描述
我正在使用mongodb的节点驱动程序在具有许多不断更新的字段的文档上启动更改流(通过插入/更新端的某些逻辑,该逻辑仅调用 $ set (已更改的字段),但我只想关注特定字段的更改.我目前的尝试是在下面,但是即使该字段不是更新的一部分,我也可以获取每个更新.
I am using the node driver for mongodb to initiate a change stream on a document that has lots of fields that update continuously (via some logic on the insert/update end that calls $set with only the fields that changed), but I would like to watch only for changes to a specific field. My current attempt at this is below but I just get every update even if the field isn't part of the update.
我认为"updateDescription.updatedFields"是我想要的,但是到目前为止,我提供的代码只是为我提供了所有更新.
I think the "updateDescription.updatedFields" is what I am after but the code I have so far just gives me all the updates.
要实现这样的目标,正确的$ match过滤器会是什么样?我以为也许检查一下它是否是$ gte:1可能是使它正常工作的一种方法,但我仍然只是获得所有更新.我试过$ inc来查看字段名称是否也在"updatedFields"中,但这似乎也不起作用.
What would the proper $match filter look like to achieve something like this? I thought maybe checking if it's $gte:1 might be a hack to get it to work but I still just get every update. I've tried $inc to see if the field name is in "updatedFields" as well but that didn't seem to work either.
const MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb://localhost:27017/?replicaSet=rs0';
MongoClient.connect(uri, function(err, client) {
const db = client.db('mydb');
// Connect using MongoClient
var filter = {
$match: {
"updateDescription.updatedFields.SomeFieldA": { $gte : 1 },
operationType: 'update'
}
};
var options = { fullDocument: 'updateLookup' };
db.collection('somecollection').watch(filter, options).on('change', data => {
console.log(new Date(), data);
});
});
推荐答案
所以我知道了...
对于其他感兴趣的人:我的管道"(在我的示例中为过滤器)必须为数组
For anyone else interested: My "pipeline" (filter, in my example) needs to be an array
这有效...
const MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb://localhost:27017/?replicaSet=rs0';
MongoClient.connect(uri, function(err, client) {
const db = client.db('mydb');
// Connect using MongoClient
var filter = [{
$match: {
$and: [
{ "updateDescription.updatedFields.SomeFieldA": { $exists: true } },
{ operationType: "update" }]
}
}];
var options = { fullDocument: 'updateLookup' };
db.collection('somecollection').watch(filter, options).on('change', data =>
{
console.log(new Date(), data);
});
});
这篇关于如何监视MongoDB变更流中特定字段的变更的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!