[SERVER-1030] $only for feature for fields that are embedded arrays Created: 19/Apr/10  Updated: 06/Dec/22  Resolved: 19/May/17

Status: Closed
Project: Core Server
Component/s: Querying
Affects Version/s: 1.5.0
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: Stanislav Vishnevskiy Assignee: Backlog - Query Team (Inactive)
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Assigned Teams:
Query
Participants:

 Description   

Similar to the new slice functionality

db.foo.find( {} , { likes: { $only: [user_1, user_2]} } ) and it would return the list of user_ids that were found

My original idea was to recommend something like this, but mstearn recommended the one above instead.

db.foo.find( {} , { likes: { $has: user_1 } } ) and it would use return True/False

Because I just want the objects, and I want to know if the user liked each one without returning the full list of likes.



 Comments   
Comment by David Storch [ 19/May/17 ]

These use cases can now be achieved using the aggregation framework. First, the $only example can be expressed using the $filter expression, new in version 3.2:

> db.c.drop()
true
> db.c.insert({likes: ["user1", "user3", "user2"]})
WriteResult({ "nInserted" : 1 })
> db.c.aggregate([
    {$project: {filteredLikes:
        {$filter: {input: "$likes", as: "user", cond:
            {$or: [{$eq: ["$$user", "user1"]}, {$eq: ["$$user", "user2"]}]}}}
        }
    }
]);
{ "_id" : ObjectId("591f1c4b69f498d1bbd5b1cd"), "filteredLikes" : [ "user1", "user2" ] }

Second, the $has example can be accomplished using $in, added in version 3.4:

> db.c.aggregate([{$project: {hasLike: {$in: ["user1", "$likes"]}}}]);
{ "_id" : ObjectId("591f1c4b69f498d1bbd5b1cd"), "hasLike" : true }

I am therefore closing this ticket as "Gone Away".

Generated at Thu Feb 08 02:55:51 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.