0

I have the following schema, blog collection & friendscoll as below

blogpostcollection
    {
      "_id" : ObjectId("4fff0bf18bf0d19c4f1a5826"),
      "author" : "joe",
      "text" : "Here is the text...",
      "userid" : 0
    }
    {
      "_id" : ObjectId("4fff0bf18bf0d19c4f1a5827"),
      "author" : "blake",
      "text" : "Here is the text...",
      "userid" : 1
    }
    {
      "_id" : ObjectId("4fff0bf18bf0d19c4f1a5828"),
      "author" : "joe",
      "text" : "Here is the text...",
      "userid" : 2
    }

myfriendscoll
    {
      "myid": 999,
      "data": [
        {
          "uid": 1, 
          "name": "Raul"
        }, 
        {
          "uid": 3, 
          "name": "John K"
        } ]
    }

I want to find all documents in blogpostcollection, where the userid exists as uid, in the myfriendscoll collection. So in effect, something like..

var user = db.myfriendscoll.findOne({"myid" : 999}, {"data.uid": 1});
db.blogpostcollection.find( {"userid" : {$in : user.data.uid}});

This doesn't work, but is there a way to get it to work?...Thanks!

2 Answers 2

1

If you are using development version 2.1 or when you move to 2.2 once it's released you can use the aggregation framework to get the format you want back from the first query:

var ret=db.myfriendscoll.aggregate([
             {$match:{"myid" : 999}},
             {$project:{_id:0,uid:"$data.uid"}}
]);
var uids=ret.result[0].uid;
db.blogpostcollection.find({userid:{$in:uids}})
Sign up to request clarification or add additional context in comments.

Comments

0

You'll need to extract the actual uid values into an array to use with $in. Try this:

var user = db.myfriendscoll.findOne({"myid" : 999}, {"data.uid": 1});
var uids = user.data.map(function(v){ return v.uid });
db.blogpostcollection.find( {"userid" : {$in : uids}});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.