Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo db using result of query in another query using $in

I have the following model in mongo db:

User collection

{
_id:12345,
name:"Joe",
age:15,
}

Addresses collection

{
_id:7663,
userId:12345,
Street:"xyz",
number:"1235",
city:"New York",
state:"NY"
}

Now I want to get all the addresses of users above the age of 20. What I thought was to query all the ids of users above 20 and with the result of this query use the $in operator to find the addresses.

My question is, is there a way to turn this into one query? Is there a better way to query this? (obs: this is just an example, with my problem I cannot embed addresses into users)

like image 775
Eduardo Mayer Avatar asked May 13 '14 17:05

Eduardo Mayer


People also ask

How do I use $in in MongoDB?

Use the $in Operator to Match Values This query selects all documents in the inventory collection where the value of the quantity field is either 5 or 15. Although you can write this query using the $or operator, use the $in operator rather than the $or operator when performing equality checks on the same field.

Does MongoDB support query join between collections?

The MongoDB Compass GUI allows you to query, aggregate, and analyze your MongoDB data using a visual environment. The $lookup aggregation function is used to perform MongoDB Join two collections for the same database.

Does MongoDB $in Clause guarantee order?

As the references are stored in a array, it makes sense to preserve the order. MongoDB only gurantee order of documents based on a sort operation. Therefore, even if some queries will return the order you need it won't be guaranteed for every query.

What is $$ in MongoDB?

To access the value of the variable, prefix the variable name with double dollar signs ( $$ ); i.e. "$$<variable>" . If the variable references an object, to access a specific field in the object, use the dot notation; i.e. "$$<variable>.


1 Answers

In Mongo shell you can use the result of one query in another. For example:

use database  // the name of your database
db.coll1.find({_id:{$nin:db.coll2.distinct("coll1_id")}})

Here collection coll1 contains an _id field. Then you can check for any ids that are not in collection coll2's list of the coll1_id field. So this is a way to clean up two tables if you have records in coll1 which have no reference via the coll1_id field in coll2.

Another approach doing the same thing:

use database  // the name of your database
temp = db.coll2.distinct("coll1_id");
db.coll1.find({_id:{$nin:temp}})

The first example does it in one command, the second does it in two, but the concept is the same. Using results from one query in another. Many different ways to do this. Also, the .toArray() method can be useful to create arrays if you're doing more than just using distinct().

like image 150
ciso Avatar answered Sep 20 '22 19:09

ciso