Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Find() inside Insert" in MongoDB?

Folks, I have a collection called 'Animals', example documents -

{
    "_id" : ObjectId("57321290c46ff86ce9e00b35"),
    "parent_id" : null,
    "author" : "[email protected]",
    "name" : "Mammal",
    "status" : "active",
    "sub_species" : [ 
        "Dog", 
        "Cat", 
        "Cow"
    ]
}

{
    "_id" : ObjectId("57321c10c46ff86ce9e00b36"),
    "author" : "[email protected]",
    "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" : "[email protected]",
    "name" : "Dog",
    "status" : "active",
    "parent_id" : {db.animals.find( { name: { $eq: 'Mammal' } } )}
} )

Thanks in advance

like image 337
Sanjay Das Avatar asked Nov 23 '25 11:11

Sanjay Das


1 Answers

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" : "[email protected]",
    "name" : "Dog",
    "status" : "active",
    "parent_id" : parent_id
};
db.animals.insert(insertDoc);
like image 173
chridam Avatar answered Nov 26 '25 14:11

chridam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!