Is it possible (and how) in Mongo to somehow implement a construction like @a = SELECT id FROM tableA WHERE t = 'tmp' LIMIT 1; INSERT INTO tableB (fields) VALUES (..., @a)?

of type db.collection.insert ({'title': 'TheTitle', 'otherId': db.collection.find ({'SomeField': 'Value'}) ._ id})

I read the manual of the Monga, there are all some simple examples, but nothing about the subqueries. Or do you need to manually add all the links in Monga after inserting the object?

    1 answer 1

    db.collection.findOne({}, {_id: 1})._id.str returns the document _id as a string. We use this:

    Insert one test record:

     db.collection.insert({title: 'TheTitle'}); 

    findOne returns one document, so you can insert a "link" like this:

     db.collection.insert({title: 'TheTitle 2', otherId: db.collection.findOne({}, {_id: 1})._id.str }) 

    find returns a list, so let's access a single document by index (in the example, the second document):

     db.collection.insert({title: 'TheTitle 3', otherId: db.collection.find({}, {_id: 1})[1]._id.str }) 

    The resulting collection now looks like this:

     { "_id" : ObjectId("5ca44bdc95c2f2de8583c5b8"), "title" : "TheTitle" } { "_id" : ObjectId("5ca44c1ae794d54551f16999"), "title" : "TheTitle 2", "otherId" : "5ca44bdc95c2f2de8583c5b8" } { "_id" : ObjectId("5ca44d2ae794d54551f1699a"), "title" : "TheTitle 3", "otherId" : "5ca44c1ae794d54551f16999" }