Mongodb 我们可以在mongo shell中使用回调吗?

Mongodb 我们可以在mongo shell中使用回调吗?,mongodb,mongo-shell,Mongodb,Mongo Shell,我想在collection1中插入一个文档,成功插入文档后,我想在collection2中插入另一个文档。collection2中文档的一个字段将是刚刚插入collection1的文档的\u id 我正在使用回调: db.collection1.insert(<document>,function(err,doc)){ db.collection2.insert({collection1_id: doc[0]._id, <field>:<value>

我想在
collection1
中插入一个文档,成功插入文档后,我想在
collection2
中插入另一个文档。
collection2
中文档的一个字段将是刚刚插入
collection1
的文档的
\u id

我正在使用回调:

db.collection1.insert(<document>,function(err,doc)){
     db.collection2.insert({collection1_id: doc[0]._id, <field>:<value>})
db.collection1.insert(,函数(err,doc)){
db.collection2.insert({collection1\u id:doc[0]。\u id,:})
但是,如果没有
Node.js
,回调似乎不可用


有什么解决方法吗?

回调是Node.js异步API的一部分,在
mongo
shell(与MongoDB 4.0一样)中不受支持。但是,您可以在不使用回调的情况下编写等价的回调

mongo
shell方法将返回一个带有插入文档的
\u id
值的
insertedId
字段,因此您可以保存或引用该值

例如:

db.collection2.insertOne({
    collection1_id: db.collection1.insertOne({}).insertedId,
    field: 'value'
})

在Mongo shell中没有node.js是什么意思?@estus,是的,在Mongo shell中还是仅仅在命令行中?如何实际使用此值?@user1767316答案中有一个例子引用了新文档的
insertedId
db.collection1.insertOne({}).insertedId
。如果这不是您想要的,我建议您提出一个新问题,并提供相关详细信息。