英文:
Matching property from array of objects in MongoDB aggregation query
问题
在MongoDB中,我有一个集合,其中字段'abc'是一个对象数组,格式如下:
'abc': [{"_id": new ObjectId("someId"), "name": "entity name"}]
我想要进行聚合操作(不能使用.find()),其中我传递值以匹配_id属性。
类似以下的查询不起作用:
{ $match: { 'abc._id': { $in: ['someId', 'someId2']} }}
我尝试了多种在互联网上找到的方法,但没有任何效果。
是否有人知道如何使用聚合函数来实现这个操作?
英文:
In mongoDB I have collection where field 'abc' is array of objects like this:
'abc': [{"_id": new ObjectId("someId"), "name": "entity name"}]
I want to make aggregation (it cannot be .find()) where I pass value to match _id property
Something like this does not work
{ $match: { 'abc._id': { $in: ['someId', 'someId2']} }}
I tried multiple ways I found on Internet but nothing worked.
Does anyone know how to do this using aggregate function?
答案1
得分: 1
首先,Aggregate 接受一个数组。
解决方案:
你必须使用Mongo的 ObjectId 来包装 ids。
const mongoose = require('mongoose')
const ObjectId = mongoose.Schema.Types.ObjectId
const ids = ['someId1', 'someId2'].map(id => ObjectId(id))
const pipeline = [{$match: {_id: {$in: ids }}}]
<你的模型>.aggregate(pipeline, (err, docs) => console.log({err, docs}))
英文:
First of all, Aggregate takes an array.
Solution:
You must wrap ids with Mongo ObjectId.
const mongoose = require('mongoose')
const ObjectId = mongoose.Schema.Types.ObjectId
const ids = ['someId1', 'someId2'].map(id => ObjectId(id))
const pipeline = [{$match: {_id: {$in: ids }}}]
<your model>.aggregate(pipeline, (err, docs) => console.log({err, docs}))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论