繁体   English   中英

MongoDB 中的“Find() inside Insert”?

[英]“Find() inside Insert” in MongoDB?

伙计们,我有一个名为“动物”的集合,示例文档-

{
    "_id" : ObjectId("57321290c46ff86ce9e00b35"),
    "parent_id" : null,
    "author" : "xxx@hotmail.com",
    "name" : "Mammal",
    "status" : "active",
    "sub_species" : [ 
        "Dog", 
        "Cat", 
        "Cow"
    ]
}

{
    "_id" : ObjectId("57321c10c46ff86ce9e00b36"),
    "author" : "xxx@hotmail.com",
    "name" : "Dog",
    "status" : "active",
    "parent_id" : "57321290c46ff86ce9e00b35"
}

我的问题是 - 如何在 mongo shell 中编写 Insert-statement 以编程方式生成“parent-id”(如果它已经存在)? 我希望能够写出这样的东西 -

db.animals.insert( {
    "author" : "xxx@hotmail.com",
    "name" : "Dog",
    "status" : "active",
    "parent_id" : {db.animals.find( { name: { $eq: 'Mammal' } } )}
} )

提前致谢

这是不可能的,因为 mongo shell 只是 MongoDB 服务器的交互式 JS 接口,因此您需要在执行插入之前对父 ID 进行单独的查询; 您不能在插入文档中包含查询操作。

以下示例演示了这一点:

var parent_id = db.animals.findOne({ name: 'Mammal' })._id;
var insertDoc = {
    "author" : "xxx@hotmail.com",
    "name" : "Dog",
    "status" : "active",
    "parent_id" : parent_id
};
db.animals.insert(insertDoc);

试试吧...

db.animals.insert( {
   "author" : "xxx@hotmail.com",
   "name" : "Dog",
   "status" : "active",
   "parent_id" : db.animals.findOne( { "name": "Mammal" } )
} )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM