mongodb 使用 Mongo 查询数组对象中的字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17075205/
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:17:07  来源:igfitidea点击:

Query for a field in an object in array with Mongo?

mongodb

提问by user1816679

Is it possible to use Mongo to query for entries that have a particular value in a field in an object in an array.

是否可以使用 Mongo 查询在数组对象的字段中具有特定值的条目。

For example, let's say I want to find all objects where field1 has an array of objects, one of which has the field 'one' with a value of 1. This query should return the following object from my collection:

例如,假设我想查找 field1 具有对象数组的所有对象,其中一个具有值为 1 的字段“one”。此查询应从我的集合中返回以下对象:

{_id: 0000, field1: [{one: 1, two: 2}, {one: 'uno', two: 'dos'}]}

回答by Lucia Pasarin

I suppose what you need is:

我想你需要的是:

db.collection.find( { field1: { $elemMatch: { one: 1 } } } );

http://docs.mongodb.org/manual/reference/operator/elemMatch/#op._S_elemMatch

http://docs.mongodb.org/manual/reference/operator/elemMatch/#op._S_elemMatch

回答by JohnnyHK

This is an old question, but a simpler way to perform this query is to use dot notation:

这是一个老问题,但执行此查询的更简单方法是使用点表示法

db.collection.find({'field1.one': 1})