Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

I am having a user document collection like the following:

User {

   id:"001"

   name:"John",

   age:30,

   friends:["?) order by age

I want to have something similar in MongoDB can somebody help me?

1 Answer

0 votes
by (107k points)

Note that the following solution only applies to versions of MongoDb prior to v3.2.

You can't do what you want in just one query. First you have to retrieve the list of friend user ids, then pass those ids to the second query to retrieve the documents and sort them by age.

var user = db.user.findOne({"id" : "001"}, {"friends": 1})

db.user.find( {"id" : {$in : user.friends }}).sort("age" : 1);

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
asked Oct 18, 2019 in Web Technology by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...