Mongodb: the best way to get specific documents and then the rest

says that I have 1000 documents that have:

user_id
text

Now I would like to pull out all of these documents, but first pull out the documents from several specific users (given the array of user IDs), and then all the rest.

I thought of using a map abbreviation to create a new inline weight attribute if user_id exists in a specific user array (using the scope to pass the array), and then to sort this new attribute. But from what I could understand, you cannot sort after reducing the map.

Does anyone have a good suggestion on how to do this? Any suggestion would be welcome.

Thank!

+2
source share
1 answer

Well, there are not many details here, but I can give an example to consider. Consider the following set of documents:

{ "user" : "fred", "color" : "black" }
{ "user" : "bill", "color" : "blue" }
{ "user" : "ted", "color" : "red" }
{ "user" : "ted", "color" : "black" }
{ "user" : "fred", "color" : "blue" }
{ "user" : "bill", "color" : "red" }
{ "user" : "bill", "color" : "orange" }
{ "user" : "fred", "color" : "orange" }
{ "user" : "ted", "color" : "orange" }
{ "user" : "ally", "color" : "orange" }
{ "user" : "alice", "color" : "orange" }
{ "user" : "alice", "color" : "red" }
{ "user" : "bill", "color" : "purple" }

So, suppose you want to bubble items for the users "bill" and "ted" at the top of your results, and then all the rest, sorted by userand color. What you can do is run the documents using $ project together as follows:

db.bubble.aggregate([

    // Project selects the fields to show, and we add a weight value
    {$project: {
        _id: 0,
        "user": 1,
        "color": 1,
        "weight": {$cond:[
            {$or: [
                {$eq: ["$user","bill"]},
                {$eq: ["$user","ted"]}
            ]},
            1,
            0
         ]}
     }},

    // Then sort the results with the `weight` first, then `user` and `color`
    {$sort: { weight: -1, user: 1, color: 1 }}

])

, , weight user . , , 0.

$sort, weight , "" , - .

, $project . . :

http://docs.mongodb.org/manual/reference/operator/aggregation/

+4

Source: https://habr.com/ru/post/1530191/


All Articles