在MongoDB聚合查询中匹配数组对象的属性。

huangapple go评论75阅读模式
英文:

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(&#39;mongoose&#39;)
const ObjectId = mongoose.Schema.Types.ObjectId
const ids = [&#39;someId1&#39;, &#39;someId2&#39;].map(id =&gt; ObjectId(id))
const pipeline = [{$match: {_id: {$in: ids }}}]

&lt;your model&gt;.aggregate(pipeline, (err, docs) =&gt; console.log({err, docs}))

huangapple
  • 本文由 发表于 2023年6月22日 05:16:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527195.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定