Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

488
Views
Búsqueda de agregación de MongoDB en objetos de matriz [nodejs, mangosta]

Obtengo del lado del cliente un objeto de filtro como:

 { appId: "01", items: [ '60522e84feecf7036fa11831', '60522c47feecf7036fa1182d' ], //offset limit }

mi consulta es:

 await someCollection.aggregate([ { $match: query }, { $group: {//some fields} }, ]) .sort({date: -1}) .skip(+req.query.offset) .limit(+req.query.limit)

colección es:

 [ { "_id": 1, "shop": 1, "appId": "01", "items": [ { "itemId": "777" }, { "itemId": "666" }, ] }, { "_id": 2, "shop": 2, "appId": "01", "items": [ { "itemId": "666" }, { "itemId": "123" }, ] }, { "_id": 3, "shop": 2, "appId": "01", "items": [ { "itemId": "x" }, ] } ]

en mi consulta Backend genera dinámicamente :

 const query = { '$expr':{ '$and':[ {'$eq': ['$appId', req.user.appId.toString()]}, ] } }

Si la consulta entrante tiene una matriz de productos , necesito buscar las identificaciones en la matriz de objetos . por ejemplo: ['777', 'x'] como resultado debe tener 2 elementos donde "_id": 1 y "_id": 3

mi código es:

 if(req.query.products) { typeof req.query.products === 'string' ? req.query.products = [req.query.products] : req.query.products let bb = req.query.products.map(function(el) { return mongoose.Types.ObjectId(el) }) query['$expr']['$and'].push({ $or: [{ $eq: ['$items.itemId', bb] }], } }

parque infantil mongo

entonces, necesito usar el operador $in con $match & $and dinámicamente, pero no tengo idea de cómo

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Yo lo intentaría así:

 const query = { ['$or']: [] } for (let k of Object.keys(req.user)) { if (Array.isArray(req.user[k])) { for (let i in req.user[k]) query['$or'].push({ [`${k}.itemId`]: mongoose.Types.ObjectId(i) }); } else { query[k] = req.user[k].toString(); } } await someCollection.aggregate([ { $match: query }, { $group: {//some fields} }, ])
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!