我如何在MongoDB中实现子查询

时间:2018-12-19 10:40:58

标签: mongodb

我有一条这样的SQL语句:

    SELECT name 
   FROM CUSTOMERS 
   WHERE ID IN (SELECT ID 
         FROM CUSTOMERS 
         WHERE SALARY > 4500) 

但是我很好奇如何在MongoDB中实现相同的查询

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用带有$gt (greater than) operator的简单查找查询,如下所示:

db.customers.find({salary: {$gt: 4500}}, {name: 1})

// {salary: {$gt: 4500}} will only return customer documents which have a 'customer.salary' that's greater than 4500 ($gt)
// {name: 1} will create a projection with only the name. (you might have to filter the mandatory _id field, if you only want the name, though.)