How to get a field value from a collection in shell db script?

mongo
mongo
170 Points
8 Posts

I'm writing mongo db script for data migration. And want to get a value from a collection and then use it in other command in the same db migration script. 

I'm trying some thing:

var roleId= '54612sdfd54521'; // Get from roles collection role=default

db.getCollection('users').insertMany([{
    "_id" : "25ea8b80-sdfsdfsd-erwer-3c234f00e8c0",
    "name" : "name 1",
    "roleId" : roleId,
}]);
Views: 1107
Total Answered: 1
Total Marked As Answer: 1
Posted On: 06-Aug-2021 04:10

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
4916 Points
27 Posts
         

Use projection in db.collection.find() as something:

var roles = db.getCollection('roles').find({"role":";default"},"{"_id":1}");

And then use like following:

db.getCollection('users').insertMany([{ 
    "_id" : "25ea8b80-sdfsdfsd-erwer-3c234f00e8c0",
    "name" : "name 1",
    "roleId" : roles[0]._id,
}]);

 

Reference: https://docs.mongodb.com/manual/reference/method/db.collection.find/

Posted On: 06-Aug-2021 23:21
Thanks
 - mongo  09-Aug-2021 20:48
 Log In to Chat