[英]“Find() inside Insert” in MongoDB?
Folks, I have a collection called 'Animals', example documents -伙计们,我有一个名为“动物”的集合,示例文档-
{
"_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"
}
My question is this - How do I write an Insert-statement in mongo shell to programmatically generate the 'parent-id' (if it already exists) ?我的问题是 - 如何在 mongo shell 中编写 Insert-statement 以编程方式生成“parent-id”(如果它已经存在)? I want to be able to write something like this -我希望能够写出这样的东西 -
db.animals.insert( {
"author" : "xxx@hotmail.com",
"name" : "Dog",
"status" : "active",
"parent_id" : {db.animals.find( { name: { $eq: 'Mammal' } } )}
} )
Thanks in advance提前致谢
That's not possible as mongo shell is just an interactive JS interface to MongoDB server hence you would need to make a separate query for the parent id before doing the insert;这是不可能的,因为 mongo shell 只是 MongoDB 服务器的交互式 JS 接口,因此您需要在执行插入之前对父 ID 进行单独的查询; you cannot include the query operation within the insert document.您不能在插入文档中包含查询操作。
The following example demonstrates this:以下示例演示了这一点:
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);
Just try...试试吧...
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.