0 votes
1 view
in Web Technology by (36.3k 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 (78.7k 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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...