mongodb - MongoDB: Aggregate the index value in array of objects with element value of 'x'
问题描述
I'm trying to work from this part of the documentation: https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfArray/
and my use case is almost identical except instead of having an array of values I have an array of objects:
{ "_id" : 1, "items" : [
{x: "one", y: "two", z: "three"},
{x: "four", y: "five", z: "six"},
{etc...}
]}
The example give the following example: db.inventory.aggregate([{$project: {index: {$indexOfArray: [ "$items", 2 ] }}}]
The 2
being the search expression to find withing the array expression of $items
.
My problem is because I am trying to find the index of the object where element y equals myVariableValue. Been trying many different combinations rearranging the syntax but haven't had return anything except -1 which means it was not found.
db.collection.aggregate([
{$match: {_id: id}},
{$project: {index: {$indexOfArray: [ "$items", {y: myVariableValue} ] }}}
]);
Doesn't seem to work and thought it definitely would.
What is the correct search syntax I am looking for to return the correct value of the index? Thanks!
解决方案
Your $indexOfArray
syntax must be like this:
{
$project: {
index: {
$indexOfArray: [
"$items.y",
myVariableValue
]
}
}
}
It would be good, if an example existed for an array of objects in the mongodb docs.
推荐阅读
- matlab - 如何在 MATLAB 图中围绕平铺对象绘制矩形?
- google-cloud-platform - GCP 零 BLEU 分数
- unity3d - Unity - NavMesh 不会烘烤楼梯
- elasticsearch - 如何使用python在elasticsearch中按未存储的字段进行过滤
- flutter - 我的用户如何在我的 Flutter 应用程序中相互汇款?
- python - 如何将浮点数列表转换为百分比列表?
- anypoint-studio - 无法安装 DevKit 插件
- gremlin - 如何在 Gremlin 中找到至少有一个单向链接的顶点?
- python - Python - 为日期范围生成 url - 如果年份低于 2019,则输出 0 结果
- c# - redis 获取多个键的值,该值是在单个查询中设置的哈希值?