Mongo db using query result in another query using $ in

I have the following model in mongo db:

User collection

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

Address Collection

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

Now I want to get all the addresses of users older than 20 years. I thought that I need to request all user IDs older than 20, and as a result of this query, the $ in operator will find the addresses.

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

+6
source share
3 answers

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

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

Here the coll1 collection contains the _id field. Then you can check for any identifiers that are not in the coll2 list of the list of the coll1_id field. Thus, this is a way to clear two tables if you have entries in coll1 that do not have a link through the coll1_id field in coll2.

Another approach does the same:

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

The first example is executed in one command, the second in two, but the concept is the same. Using the results of one query in another. Many different ways to do this. In addition, the .toArray () method can be useful for creating arrays if you are doing more than just using distinct ().

+5
source

you can do this only at the application level - this means that all users will be in one request, receive all addresses in another and glue them together. Mongo does not do what you ask.

0
source

Use the aggregation infrastructure, where the $lookup stage provides the functionality of combining two collections:

 db.user.aggregate([ { "$match": { "age": { "$gt": 20 } } }, { "$lookup": { "from": "addresses", "localField": "_id", "foreignField": "userId", "as": "address" } } ]) 

The above will create a new array field called address (as indicated in $lookup as an option), and this contains the relevant documents from the collection addresses. If the specified name already exists in the input document, the existing field is overwritten.

0
source

All Articles