查询 MongoDB 以匹配数组中的第一项 [英] Querying MongoDB to match in the first item in an array

查看:30
本文介绍了查询 MongoDB 以匹配数组中的第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm aware of the $in operator, 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.

例如:

{
    "_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"})

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

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

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

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

推荐答案

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

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

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

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

这篇关于查询 MongoDB 以匹配数组中的第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆