这个是node里的,用$push操作符:
const { MongoClient } = require('mongodb');
async function appendMsg(tag, msg) {
const client = new MongoClient('mongodb://localhost:27017', { useUnifiedTopology: true });
await client.connect();
try {
const db = client.db('yourDatabaseName');
const collection = db.collection('yourCollectionName');
// 开始事务
const session = client.startSession();
session.startTransaction();
try {
let doc = await collection.find({ tag: tag }).sort({ id: -1 }).limit(1).toArray();
doc = doc[0];
if (!doc) {
doc = { id: `${tag}:0`, tag: tag, msg: [] };
await collection.insertOne(doc, { session });
}
if (doc.msg.length < 10) {
// 如果数组长度小于10,向数组中追加元素
await collection.updateOne({ id: doc.id }, { $push: { msg: msg } }, { session });
} else {
// 如果数组长度达到10,创建新的文档并向其数组中追加元素
const newId = `${tag}:${parseInt(doc.id.split(':')[1]) + 1}`;
const newDoc = { id: newId, tag: tag, msg: [msg] };
await collection.insertOne(newDoc, { session });
}
// 提交事务
await session.commitTransaction();
} catch (err) {
// 如果有错误,则中止事务
await session.abortTransaction();
throw err;
} finally {
// 结束会话
session.endSession();
}
} finally {
// 关闭连接
await client.close();
}
}
appendMsg('a', 'new message').catch(console.error);