0

I'm currently working on a matching algorithm that calculates a score between two differents products lists.
I'm using mongodb aggregations to add a matching-score field calculated with differents arguments. Actually, the algorithm needs to know the position of each product in the list. So I thought to dynamically add a position field on each product to use it later.
I don't know which mongodb aggregation operator I have to use. Maybe someone can help me ?

Here is my list model :

const listSchema = mongoose.Schema({
    type: { type: mongoose.Schema.Types.ObjectId, ref: "ListType", required: true },
    links: [{
        brand: { type: mongoose.Schema.Types.ObjectId, ref: "Brand", required: true },
        work: { type: mongoose.Schema.Types.ObjectId, ref: "Product" },
    }],
    associatedUser: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true }
}, { versionKey: false });

In advance thank you,
Pierre

2

1 Answer 1

1

One method is to use the $reduce operator, which can be done in an aggregation pipeline, or as of MongoDB 4.2 in an update.

This example replaces an 'arrayField' containing

["Hello","World"]

with an array of objects like

[{index:0,value:"Hello"},{index:1,value:"World"}]
db.collection.update({},[{$set:{
      arrayField:{
            $reduce:{
                 input:"$arrayField",
                 initialValue:[],
                 in:{ $push:[
                       "$$value",
                       {index:{$size:"$$value"},
                        value:"$$this"}
                 ]}
            }
     }
}}])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.