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

查看:357
本文介绍了查询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天全站免登陆