Skip to main content

MongoDB - Generating dynamic $or using pipeline variable?

hoping someone can help as I am truly stuck!

I have this query

SwapModel.aggregate([
    {
        $match: {
            organisationId: mongoose.Types.ObjectId(organisationId),
            matchId: null,
            matchStatus: 0,
            offers: {
                $elemMatch: {
                    from: { $lte: new Date(from) },
                    to: { $gte: new Date(to) },
                    locations: { $elemMatch: { $eq: location } },
                    types: { $elemMatch: { $eq: type } },
                },
            },
//problem is HERE
            $or: {
                $map: {
                    input: "$offers",
                    as: "offer",
                    in: {
                        from: { $gte: new Date("$$offer.from") },
                        to: { $lte: new Date("$$offer.to") },
                        location: { $in: "$$offer.locations" },
                        type: { $in: "$$offer.types" },
                    },
                },
            },
        },
    },
    { ...swapUserLookup },
    { $unwind: "$matchedUser" },
    { $sort: { from: 1, to: 1 } },
]);

I'm trying to use the results of the $match document to generate an array for $or. My data looks like this:

[{
    _id: ObjectId("507f1f77bcf86cd799439011"),
    from: ISODate("2023-01-21T06:30:00.000Z"),
    to: ISODate("2023-01-21T18:30:00.000Z"),
    matchStatus: 0,
    matchId: null,
    userId: ObjectId("ddbb8f3c59cf13467cbd6a532"),
    organisationId: ObjectId("246afaf417be1cfdcf55792be"),
    location: "Chertsey",
    type: "DCA",
    offers: [{
        from: ISODate("2023-01-23T05:00:00.000Z"),
        to: ISODate("2023-01-24T07:00:00.000Z"),
        locations: ["Chertsey", "Walton"],
        types: ["DCA", "SRV"],
    }]
}, {
    _id: ObjectId("21575faf348660e8960c0d931"),
    from: ISODate("2023-01-23T06:30:00.000Z"),
    to: ISODate("2023-01-23T18:30:00.000Z"),
    matchStatus: 0,
    matchId: null,
    userId: ObjectId("d6f10351dd8cf3462e3867f56"),
    organisationId: ObjectId("246afaf417be1cfdcf55792be"),
    location: "Chertsey",
    type: "DCA",
    offers: [{
        from: ISODate("2023-01-21T05:00:00.000Z"),
        to: ISODate("2023-01-21T07:00:00.000Z"),
        locations: ["Chertsey", "Walton"],
        types: ["DCA", "SRV"],
    }]
}]

I want the $or to match all documents that have the corresponding from/to/location/type as the current document - the idea is two shifts that could be swapped

If the offers are known (passed as an array to the function calling aggregate), I can do this with:

$or: offers.map((x) => ({
            from: { $gte: new Date(x.from) },
            to: { $lte: new Date(x.to) },
            location: { $in: x.locations },
            type: { $in: x.types },
        }))

BUT I want to be able to do this in an aggregation pipeline when the offers will only be known from the current document, $offers

Is this possible? I've tried $in, $map, $lookup, $filter, $getField but can't get it right and can't get anything from Google as it thinks I want $in (which is the opposite of what I need).

I'm pretty new to MongoDB and am probably approaching this completely wrong but I'd really appreciate any help!

Via Active questions tagged javascript - Stack Overflow https://ift.tt/MqyfUEt

Comments

Popular posts from this blog

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...