MongoDB:$elemMatch [英] MongoDB: $elemMatch

查看:34
本文介绍了MongoDB:$elemMatch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 $elemMatch 在数组中查找对象.我将以下数据导入到名为 trails 的集合中:

I'm trying to use $elemMatch to find an object in an array. I imported the following data into a collection named trails:

{ "Copper" : [
        {"name" : "Spaulding Bowl", "level" : "Extreme Terain", "location" : "East Side"},
        {"name" : "Resolution Bowl", "level" : "Double Black", "location" : "East Side"},
        {"name" : "Black Bear Glade", "level" : "Double Black", "location" : "East Side"},
        {"name" : "Free Fall Glade", "level" : "Double Black", "location" : "East Side"}
 ]
}

我正在使用 MongoDB 文档中的语法 进行以下查询:

I'm using the syntax from the MongoDB documentation to make the following query:

db.trails.find( { "Copper": { $elemMatch: { "name" : "Spaulding Bowl" } }  } )

我也尝试过在键周围不加引号的情况下对其进行格式化:

I have also tried formating it without quotations around the keys:

db.trails.find( { Copper: { $elemMatch: { name : "Spaulding Bowl" } }  } )

不是只返回一个匹配的元素,而是返回整个对象数组.是否有我遗漏的语法错误?感谢所有提示.

Instead of returning just one matching element, both return the entire array of objects. Is there a syntax error I'm missing? All tips are appreciated.

推荐答案

$elemmatch(query) 当至少有一行符合查询条件时,返回数组中的所有行.

$elemmatch(query) returns all rows in a array when there is atleast one row matching the query criteria.

$elemMatch(projection) 用作投影时仅返回所有匹配行的第一行.

$elemMatch(projection) returns only the first row of all the matching rows when used as projection.

您的案例不需要 elemMatch,因为它只是单一标准.

You don't need elemMatch for your case as it is only single criteria.

db.trails.find({"Copper.name": { "Spaulding Bowl" } })

尝试如下使用 elemMatch 投影变化.

Try as below which uses the elemMatch projection variation.

db.trails.find({}, {"Copper": { $elemMatch: { "name" : "Spaulding Bowl" } }  } )

这篇关于MongoDB:$elemMatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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