MongoDB sort by relevance

I am trying to get documents from MongoDB on node. Let them say that documents have the following structure:

{ "_id": ObjectId, "title" : String, "tags" : Array<String> }

I would like to sort them by relevance - so when I look for documents that have either a blue or yellow tag, I would like to get them with both tags first. So far, I have been controlled by Google, trial version and error:

var tags = [ "yellow", "blue" ];
db.collection('files').aggregate([
    { $project : { tags: 1 } },
    { $unwind : "$tags" },
    { $match : { "tags": { "$in": tags } } },
    { $group : { _id: "$_id", relevance: { $sum:1 } } },
    { $sort : { relevance : -1 } },
], function(err, success) {
    console.log(success);
});

This works fine, I get a sorted collection of identifiers:

[{"_id":"5371355045002fc820a09566","relevance":2},{"_id":"53712fc6c8fcd124216de6cd","relevance":2},{"_id":"5371302ebd4725dc1b908316","relevance":1}]

Now I would make another request and ask for documents with these identifiers, but here is my question: can it be done in one request?

+4
source share
1 answer

, , , _id, . , _id.

MongoDB, MongoDB 2.6 $project (, $match ) , :

var tags = ["yellow","blue"];
db.collection.aggregate([
    { "$project" : { 
        "_id": {
            "_id": "$_id",
            "title": "$title",
            "tags": "$tags"
        },
        "tags": 1 
    }},
    { "$unwind": "$tags" },
    { "$match": { "tags": { "$in": tags } } },
    { "$group": { "_id": "$_id", "relevance": { "$sum":1 } } },
    { "$sort": { "relevance" : -1 } },
    { "$project": {
        _id: "$_id._id",
        "title": "$_id.title",
        "tags": "$_id.tags"
    }}
])

, , _id, . , .

MongoDB 2.6 , , , $$ROOT, :

var tags = ["yellow","blue"];
db.collection.aggregate([
    { "$project" : { 
        "_id": "$$ROOT",
        "tags": 1 
    }},
    { "$unwind": "$tags" },
    { "$match": { "tags": { "$in": tags } } },
    { "$group": { "_id": "$_id", "relevance": { "$sum":1 } } },
    { "$sort": { "relevance" : -1 } },
    { "$project": {
        "_id": "$_id._id",
        "title": "$_id.title",
        "tags": "$_id.tags"
    }}
])

, .

, , "" , , $match . , , , (, "" "" ) :

db.collection.aggregate([
    { "$match": { "tags": { "$in": tags } } },
    { "$project" : { 
        "_id": {
            "_id": "$_id",
            "title": "$title",
            "tags": "$tags"
        },
        "tags": 1 
    }},
    { "$unwind": "$tags" },
    { "$match": { "tags": { "$in": tags } } },
    { "$group": { "_id": "$_id", "relevance": { "$sum":1 } } },
    { "$sort": { "relevance" : -1 } },
    { "$project": {
        _id: "$_id._id",
        "title": "$_id.title",
        "tags": "$_id.tags"
    }}
])

, , , , , .

+3

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


All Articles