Question

I have two collections( 'Companies' and 'Users' ) and when I add one new document to the collection 'Companies', (by software default) I want to create one new document on the 'Users' colection with one new administrator user, but this new user must be related to the new document in the 'Companies' collection that was previously created....

Something like 'select @@identity' on MS SQL :P

Sample data structure:

Companies. _id = ObjectId("aaaa");
         . Name = "Company name";

Users. _id = ObjectId("uuuu");
     . Name = "admin"
     . CompanyId = ????

(ObjectiId("aaaa") defined and stored by Mongo on Collection.Update, to store on Users.CompanyId)

Regards,

Luis Pedro

Was it helpful?

Solution

Instead use the MongoID (ObjectID), you could use your own PK:

When you insert the Companies document, if you explicitely declare a field named '_id', and his value, mongodb is not going to create the Object_id again, also you can store that value you declared in a variable, and reuse it for insert the document in Users collection.

or you could make a find on Companies after the insert in it, looking for the last insert, and extrapolate the id generated by the system and reuse it.

hope that helps

OTHER TIPS

To add to lese's point, you may use below snippet to find the last document

db.companies.find({},{"_id":1}).skip(db.companies.find().count()-1);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top