首页 > 解决方案 > 插入中的MongoDB子查询

问题描述

我搜索类似:

insert into B (col)
select id from anotherCollection limit 1

我对此进行了测试,但我怀疑它不起作用:

db.B.insert([
  {
    "a": "lores ipsum",
    "b": [
      db.getCollection('anotherCollection').find({},{_id:1}).limit(1)
    ]
  }
]);

有必要使用投影吗?

标签: mongodb

解决方案


你不能在 mongo db 中做到这一点,但在 javascript 或 python 中是这样的

var a = db.getCollection('anotherCollection').find({},{_id:1}).limit(1)
db.B.insert([
  {
    "a": "lores ipsum",
    "b": a
  }
]);

推荐阅读