node mongodb 根据id给子集合list添加对象 请问应该如何操作

node mongodb 根据id给子集合list添加对象 请问应该如何操作
如 给id为1的list添加对象

img

用 Node.js 和 MongoDB 的情况下根据 ID 添加一个对象到给定的子集合,可以使用 MongoDB 的 $push 操作符。
要找到给定的文档,然后使用 $push 操作符把新的对象添加到 list 字段中。
如下

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@cluster.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("reviewer");
  collection.updateOne({ id: '1' }, { $push: { list: { name: 'new object' } } }, function(err, res) {
    console.log("Document updated");
    client.close();
  });
});


在 Node.js 中使用 MongoDB 根据 id 给子集合 list 添加对象的方法如下:

1、建立 MongoDB 连接:使用 MongoDB 驱动程序连接到数据库。
2、定义模式:定义一个模式,表示集合中的文档。
3、查询父集合:使用查询操作查询父集合中拥有该 id 的文档。
4、更新子集合:使用更新操作在该文档的子集合 list 中添加一个新的对象。

使用MongoDB的$push操作符可以为子集合list添加对象。使用$elemMatch查询子文档中符合条件的第一个元素。代码示例:

db.collection('学校').updateOne({'reviewer': {$elemMatch: {id: 1}}}, 
{$push: {'reviewer.$.list': {对象}}})

其中,对象为要添加的对象。

首先,你需要使用 MongoDB 的 Node.js 驱动,并与 MongoDB 数据库建立连接。然后,执行以下操作:

选择相应的数据库和集合;
使用 findOne() 方法查询 id 为 1 的文档;
使用 push() 方法向文档的 list 字段(即子集合)添加新的对象;
使用 save() 方法保存更新后的文档。
以下是示例代码:

javascript

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const db = client.db("test");
  const collection = db.collection("documents");
  collection.findOne({ id: 1 }, function (err, doc) {
    doc.list.push({ newObject: "value" });
    collection.save(doc);
    client.close();
  });
});

注意:在上面的代码中,请将 和 替换为实际的 MongoDB 连接字符串中的用户名和密码。

不建议使用mongoDB的更新、删除等操作,Mongo优势在于查询快,但是删改慢,可以考虑不完整数据在数据库暂时存放,或者redis中暂时存放,处理后删除