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) ? 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; 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" } )
} )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.