MongoDB在查询列表中选择所有where字段值 [英] MongoDB select all where field value in a query list
问题描述
如何在MongoShell中实现以下SQL?
How to achieve below SQL in MongoShell?
Select TableA.* from TableA where TableA.FieldB in (select TableB.FieldValue from TableB)
Mongo doc给出了
Mongo doc gives some example of
db.inventory.find( { qty: { $in: [ 5, 15 ] } } )
我希望该数组可以从另一个查询中动态获取.有可能吗?
I want that array be dynamically from another query. Is it possible?
扩展我的问题
我有一个bot
个名字的集合
机器人集合
{
"_id" : ObjectId("53266697c294991f57c36e42"),
"name" : "teoma"
}
我有一个用户流量集合,在该流量集合中,我有一个字段useragent
I have a collection of user traffic, in that traffic collection, I have a field useragent
userTraffic Collection
{
"_id" : ObjectId("5325ee6efb91c0161cbe7b2c"),
"hosttype" : "http",
"useragent" : "Mediapartners-Google",
"is_crawler" : false,
"City" : "Mountain View",
"State" : "CA",
"Country" : "United States"
}
我要选择其useragent
包含任何名称的bot
集合的所有用户点击量文档
I want to select all user traffic documents where its useragent
contains any name of bot
collection
这是我想出的
var botArray = db.bots.find({},{name:1, _id:0}).toArray()
db.Sessions.find({
useragent: {$in: botArray}
},{
ipaddress:1
})
在这里,我认为它正在做等于比较,但我希望它做 %%比较
Here i believe it is doing equals to comparison, but I want it to do like %% comparison
获得结果后,我想将该结果集更新为 is_crawler = true
Once I get the result, I want to do an update to that result set as is_crawler= true
尝试过类似的操作,没有帮助
Tried something like this, isn't helpful
db.bots.find().forEach( function(myBot) {
db.Sessions.find({
useragent: /myBot.name/
},{
ipaddress:1
})
});
另一种遍历记录的方法,但是没有找到匹配项.
Another way of looping through the records, but no match found.
var bots = db.bots.find( {
$query: {},
$orderby:{
name:1}
});
while( bots.hasNext()) {
var bot = bots.next();
//print(bot.name);
var botName = bot.name.toLowerCase();
print(botName);
db.Sessions.find({
useragent: /botName/,
is_crawler:false
},{
start_date:1,
ipaddress:1,
useragent:1,
City:1,
State:1,
Country:1,
is_crawler:1,
_id:0
})
}
推荐答案
最后,这就是我能做到的方式.
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
})
}
});
}
});
这篇关于MongoDB在查询列表中选择所有where字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!