能够查询数组中的特定索引?猫鼬

Dor*_*ora 1 javascript arrays mongoose mongodb mongodb-query

例如,如果我有以下作为我的 documents

{
    "field": [
        "hello",
        "random wording",
        {
            "otherId": 3232,
            "otherId2": 32332
        }
    ],
}
Run Code Online (Sandbox Code Playgroud)

是否有可能让我们说有一个匹配的查询index 0index 2

我尝试进行查询,例如 model.find({field: "hello")似乎可以查询它。

但是,如果我想混搭,让我们说我想要做一个查询,无论比赛index 0index 2或假设中index 2的值实际上是一个object,我想查询所有"otherId2": 32332,而不是我需要整场比赛object

在此先感谢您的任何帮助或建议。

小智 5

查询恰好位于数组索引0处的值

model.find({'field.0': 'hello'})
Run Code Online (Sandbox Code Playgroud)

引用数组索引仅适用于第一级数组。

按数组索引2处的对象属性查询

model.find({'field.2.otherId': 3232})
Run Code Online (Sandbox Code Playgroud)