查询 MongoDB 以匹配数组中的第一项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19899299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:29:35  来源:igfitidea点击:

Querying MongoDB to match in the first item in an array

arraysmongodbmongodb-query

提问by JVG

I'm aware of the $inoperator, which appears to search for an item's presence in array, but I only want to find a match if the item is in the first position in an array.

我知道$in运算符,它似乎在数组中搜索某个项目的存在,但我只想在该项目位于数组的第一个位置时找到匹配项。

For instance:

例如:

{
    "_id" : ObjectId("0"),
    "imgs" : [
        "http://foo.jpg",
        "http://bar.jpg",
        "http://moo.jpg",
        ]
},
{
    "_id" : ObjectId("1"),
    "imgs" : [
        "http://bar.jpg",
        "http://foo.jpg",
        "http://moo.jpg",
        ]
}

I'm looking for a query akin to:

我正在寻找类似于以下内容的查询:

db.products.find({"imgs[0]": "http://foo.jpg"})

This would/should return the ObjectId("0")but not ObjectId("1"), as it's only checking against the first image in the array.

这将/应该返回ObjectId("0")但不ObjectId("1"),因为它只检查数组中的第一个图像。

How can this be achieved? I'm aware I could just create a separate field which contains a single string for firstImgbut that's not really what I'm after here.

如何做到这一点?我知道我可以创建一个单独的字段,其中包含一个字符串,firstImg但这并不是我真正想要的。

回答by poundifdef

I believe you want imgs.0. eg, given your example document, you want to say: db.products.find({"imgs.0": "http://foo.jpg"})

我相信你想要imgs.0。例如,鉴于您的示例文档,您想说:db.products.find({"imgs.0": "http://foo.jpg"})

Be aware that referencing array indexes only works for the first-level array. Mongo doesn't support searching array indexes any deeper.

请注意,引用数组索引仅适用于第一级数组。Mongo 不支持更深入地搜索数组索引。

回答by Lix

You can use dot notation for array indexes:

您可以对数组索引使用点表示法:

db.products.find({"imgs.0": "http://foo.jpg"})

Here is an excerpt from the relevant documentation for dot notation.

以下是点符号相关文档的摘录。

MongoDB uses the dot notation to access the elements of an array and to access the fields of a subdocument.

To access an element of an array by the zero-based index position, concatenate the array name with the dot (.) and zero-based index position, and enclose in quotes:

'<array>.<index>'

MongoDB 使用点符号来访问数组的元素和访问子文档的字段。

要按从零开始的索引位置访问数组元素,请将数组名称与点 (.) 和从零开始的索引位置连接起来,并用引号引起来:

'<array>.<index>'

Additionally, here is a link to the relevant array documentation.

此外,这里是相关阵列文档的链接。