Most efficient way to check if element exists in a set

357
March 20, 2017, at 2:56 PM

so in my MongoDB database I have a collection holding user posts.

Within that collection I have a set called "likes", which holds an array of the ids of the users that have liked that post. When querying I would like to pass a user id to my query and have a boolean in the result telling me whether the id exists in the array to see whether the user has already liked the post. I understand this would be easy to do with two queries, one to get the post and one to check if the user has liked it, but I would like to find the most efficient way to do this.

For example, one of my documents looks like this

{
    _id: 24jef247jos991,
    post: "Test Post",
    likes: ["userid1", "userid2"]
}

When I query from "userid1" I would like the return

{
    _id: 24jef247jos991,
    post: "Test Post",
    likes: ["userid1", "userid2"],
    userLiked: true
}

But when I query from let's say "userid3" I would like

{
    _id: 24jef247jos991,
    post: "Test Post",
    likes: ["userid1", "userid2"],
    userLiked: false
}
Answer 1

You can add the $addFields stage checking each of the document likes arrays against the input user.

db.collection.aggregate( [
        {
           $addFields: {
              "userLiked":{ $in: [ "$likes", "userid1"] }
           }
        }
] )
Answer 2

Starting from MongoDB 3.4 you can use the $in aggregation operator to check if an array contains a given element. You can use the $addFields operator aggregation operator to add the newly computed value to your document without explicitly including other fields.

db.collection.aggregate( [
   { "$addFields": { "userLiked": { "$in": [ "userid1", "$likes" ] } } }
])

In MongoDB 3.2, you can use the $setIsSubset operator and the square bracket [] operator to do this. The downside of this approach is that you need to manually $project all the field in your document. Also the $setIsSubset operator with de-duplicate your array which may not be what you want.

db.collection.aggregate([
    { "$project": { 
        "post": 1, "likes": 1, 
        "userLiked": { "$setIsSubset": [ [ "userid3" ], "$likes" ] } 
    }}
])

Finally if your mongod version is 3.0 or older you need to use the $literal operator instead of the [] operator.

Rent Charter Buses Company
READ ALSO
Twitter api search tweets tweeted by user

Twitter api search tweets tweeted by user

I'm trying to search tweets tweeted by a specific user, but I can't decipher the documentation

326
Node throw new Error('Can\'t set headers after they are sent.')

Node throw new Error('Can\'t set headers after they are sent.')

I am having the above problem with one of my node callsTo my knowledge this error shows if you res

396
Segmentation fault on Vuejs client - Debian Server

Segmentation fault on Vuejs client - Debian Server

Im working on a Vue AppI develop it on Windows and it works fine - no errors

654