我有 postgresql 和关系数据库的背景,我正在尝试再次给 mongo 一个机会,因为它似乎适合某些用途。 我在这个网站上做练习http://www.w3resource.com/mongodb-exercises/它对具有以下结构的文档进行操作:
{
"address": {
"building": "1007",
"coord": [ -73.856077, 40.848447 ],
"street": "Morris Park Ave",
"zipcode": "10462"
},
"borough": "Bronx",
"cuisine": "Bakery",
"grades": [
{ "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
{ "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
{ "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
{ "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
{ "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
],
"name": "Morris Park Bake Shop",
"restaurant_id": "30075445"
}
在两个练习中,您使用“坐标”数组进行操作,定义纬度和经度的条件。问题是我看不到数组的第一个组件或第二个组件在哪里受到限制。它没有具体说明......你能看出以下练习中他们要求限制纬度和另一个限制经度的区别吗?怎么具体说“coords数组的第一个分量必须小于...”或者“coords数组的第二个分量必须是...”非常感谢
编写一个 MongoDB 查询以查找不提供任何“美国”菜肴且其评分高于 70 且纬度低于 -65.754168 的餐厅。前往编辑器
db.restaurants.find( {$和: [ {“美食”:{$ne:“美国”}}, {"grades.score": {$gt : 70}}, {“地址坐标”:{$lt:-65.754168}} ] } );
编写一个 MongoDB 查询来查找不提供任何“美国”美食且得分超过 70 且不位于小于 -65.754168 的经度的餐厅。 注意:在不使用 $and 运算符的情况下执行此查询。前往编辑器
db.restaurants.find( {$查询: { “美食”:{$ne:“美国”}, “成绩.分数”:{$gt: 70}, “地址坐标”:{$lt:-65.754168} } });
最佳答案
回答你的问题,生成一个翻译这个命令的查询
"The first component of the coords array must be less than..."
或
"The second component of coords array must be...."
您需要使用 dot notation用于通过从零开始的索引位置访问数组的元素,并将数组名称与点 (.) 和从零开始的索引位置连接起来,并用引号引起来:
"<array>.<index>"
对于上面的示例,数组的第一个元素应包含经度值,第二个元素应包含纬度值。从而访问经度 你需要
"address.coord.0"
和纬度
"address.coord.1"
因此对于这两个练习,正确的查询如下:
Find the restaurants that does not prepare any cuisine of 'American' and their grade score more than 70 and latitude less than -65.754168:
db.restaurants.find({
"cuisine": { "$ne": "American "},
"grades.score": { "$gt": 70 },
"address.coord.1": { "$lt": -65.754168 }
});
Find the restaurants which does not prepare any cuisine of 'American' and achieved a score more than 70 and not located in the longitude less than -65.754168.
db.restaurants.find({
"cuisine": { "$ne": "American "},
"grades.score": { "$gt": 70 },
"address.coord.0": { "$gte": -65.754168 }
});
在上面两个例子中, $and
在指定逗号分隔的表达式列表时隐式使用。对 $and
使用显式 AND 当必须在多个表达式中指定相同的字段或运算符时,运算符是必需的。
关于MongoDB:如何在 mongodb 中对双元素数字数组的第二个元素设置条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40381240/