问题描述
我正在使用 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);
});
});
推荐答案
所以我想通了...
对于其他感兴趣的人:我的管道"(在我的示例中为过滤器)需要是一个数组
这行得通...
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 更改流中特定字段的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2