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 (108k 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

Browse Categories

...