MongoDB select all where field value in a query list

后端 未结 2 598
故里飘歌
故里飘歌 2021-01-14 20:51

How to achieve below SQL in MongoShell?

Select TableA.* from TableA where TableA.FieldB in (select TableB.FieldValue from TableB)

Mongo doc

相关标签:
2条回答
  • 2021-01-14 21:31

    Not in a single query it isn't.

    There is nothing wrong with getting the results from a query and feeding that in as your in condition.

    var list = db.collectionA.find({},{ "_id": 0, "field": 1 }).toArray();
    
    results = db.collectionB.find({ "newfield": { "$in": list } });
    

    But your actual purpose is not clear, as using SQL queries alone as the only example of what you want to achieve are generally not a good guide to answer the question. The main cause of this is that you probably should be modelling differently than as you do in relational. Otherwise, why use MongoDB at all?

    I would suggest reading the documentation section on Data Modelling which shows several examples of how to approach common modelling cases.

    Considering that information, then perhaps you can reconsider what you are modelling, and if you then have specific questions to other problems there, then feel free to ask your questions here.

    0 讨论(0)
  • 2021-01-14 21:38

    Finally this is how I could accomplish it.

    // Get a array with values for name field
    var botArray = db.bots.find({},{name:1}).toArray();
    
    // loop through another collection
            db.Sessions.find().forEach(function(sess){
                if(sess.is_crawler == false){ // check a condition
                     // loop in the above  array
                    botArray.forEach(function(b){
                    //check if exists in the array
                       if(String(sess.useragent).toUpperCase().indexOf(b.name.toUpperCase()) > -1){
                            db.Sessions.update({ _id : sess._id} // find by _id
                            ,{
                                is_crawler : true // set a update value
                                },
                                {
                                    upsert:false // do update only
                                })
                        } 
                      });
                }
            });
    
    0 讨论(0)
提交回复
热议问题