[英]MongoDB query of array of documents returning all elements
我有一個名為“ cupcakes”的集合,該集合是使用mongoimport從GeoJSON文件加載的 。 GeoJSON可以在此處找到,它是已知的有效JSON文件。 這部分似乎已經計划好了,正在做:
use cupcakes
db.cupcakes.find({ })
這將按預期拉回所有功能。 但是,我正在嘗試執行一個查詢,該查詢將僅返回將無麩質設置為“ no”的功能。
我已經嘗試過根據有關查詢文檔數組的文檔中的說明進行操作 。
db.cupcakes.find({features: { $elemMatch: { "properties.gluten free":"no"}}}).pretty()
但據我所知,這似乎是在返回所有功能,而不僅僅是不含麩質的功能。
本質上,我想撤回所有將“ properties.gluten free”功能設置為“ no”(或就此而言“ yes”)的功能。
示例輸出可能是:
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-122.70069837570189,
45.53570881624427
]
},
"properties": {
"name": "Le Cookie Monkey",
"address": "1902 NW 24th Avenue",
"website": "http://www.lecookiemonkey.com/",
"gluten free": "no",
"open1": "Tuesday - Friday, 9am - 3pm",
"open2": "Saturday, 9am - 2pm"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-122.6375323534012,
45.5219957171348
]
},
"properties": {
"name": "Crema Coffee + Bakery",
"address": "2728 SE Ankeny Street",
"website": "http://www.cremabakery.com/",
"gluten free": "no",
"open1": "Monday - Sunday, 7am - 6pm"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-122.60960519313811,
45.472775425296014
]
},
"properties": {
"name": "Mehri's Bakery & Deli",
"address": "6923 SE 52nd Avenue",
"website": "http://www.mehris.com/",
"gluten free": "no",
"open1": "Monday - Friday, 7am - 7pm",
"open2": "Saturday, 8am - 5pm",
"open3": "Sunday, 8am - 2pm"
}
},
...等等,直到返回“無麩質”:“否”的所有功能。
我在這里想念什么? 提前致謝。
您忘記在投影中添加positional $
運算符,該運算符將查詢結果中的features
數組的內容限制為僅包含與查詢文檔匹配的第一個元素,如下所示:
db.cupcakes.find(
{ "features.properties.gluten free": "no" },
{ "features.$": 1, "_id": 0 }
);
樣本輸出:
/* 0 */
{
"features" : [
{
"type" : "Feature",
"geometry" : {
"type" : "Point",
"coordinates" : [
-122.653357386589,
45.51208367658516
]
},
"properties" : {
"name" : "Hungry Heart Cupcakes",
"address" : "1212 SE Hawthorne Boulevard",
"website" : "http://www.hungryheartcupcakes.com",
"gluten free" : "no",
"open1" : "Monday - Sunday, 11am - 9pm"
}
}
]
}
要$redact
無麩質等於no的所有功能,在這種情況下, 聚合框架中的$redact
管道運算符應為您工作。 這將遞歸地遍歷文檔結構,並基於對每個級別上指定條件的評估來執行一些操作。 然后, map()
方法將根據期望生成最終的對象數組。 掌握這個概念可能有些棘手,但以下示例對此進行了說明:
db.cupcakes.aggregate([
{
"$match": { "features.properties.gluten free" : "no" }
},
{
"$redact": {
"$cond": {
"if": {
"$eq": [ "$gluten free", "yes" ]
},
"then": "$$PRUNE",
"else": "$$DESCEND"
}
}
}
]).map(function(doc){ return doc.features; });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.