carboncomputed
carboncomputed

Reputation: 1620

How to project the $in operator as a boolean in mongodb?

feed = coll.aggregate([
    {'$project' :{'Upvoted' : 
                            {'Upvoters'  : {'$in' : [ObjectId(userid)]} }}},
    {'$match' :{ '$or': [ {"_id": ObjectId(userid) }, {"Friends": ObjectId(userid) } ] } },
    {'$unwind' : "$Wall" },
    {'$sort' :  { "Wall.Hotness" : -1 }},
    {'$limit' : numResults }] )

I'm trying to project whether a user has upvoted or not. I do this by checking if a user is in the upvoters list. It errors saying invalid opererator $in currently. Is there an alternative to in that returns a boolean in mongo?

Upvotes: 1

Views: 468

Answers (1)

Stennie
Stennie

Reputation: 65383

You're getting an error trying to use $in with a $project because $in is only a valid operator for a $match pipeline stage.

I don't think you actually need an explicit "boolean" for your aggregate: you just want to match all documents where this property is true.

Example aggregate:

var currentUser = ObjectId("517ae8124bc9ade96ca6403f");
var numResults = 10;

db.feed.aggregate(

    // Find all posts that currentUser has upvoted
    { $match: {
        'Upvoters'  : currentUser
    }},

    // Unwind the wall messages
    { $unwind : "$Wall" },

    // Sort by hotness (descending)
    { $sort : { "Wall.Hotness" : -1 } },

    // Limit results
    { $limit : numResults }

)

Upvotes: 1

Related Questions