Mongo 数据库查询至少一个 属性 但更理想的是所有

Mongo DB query at least one property but preferred more ideally all

     "structure":{  
            "country":{  
               "name":"Some Country"
            },
            "city":{  
               "name":"Some City"
            },
            "building":{  
               "name":"Some Building"
            },
            "floor":{  
               "name":""
            }
       }

我有一个像上面这样的对象集合。我需要查询集合,因此它只会产生一个项目。

查询应包括所有四个字段的过滤器:国家、城市、建筑和楼层。

如果所有四个都匹配,那就是理想情况。

如果集合中没有这样的对象,查询应该 return 项有 3 个匹配项,一个为空。

如果没有三个比两个匹配,另外两个应该是空的。

只匹配一个字段也是一样。

重要的是其他不匹配的字段为空。不是任何不匹配的值,而是完全“”空 space.

如何为此编写 mongo 查询?

查询对我来说是这样的:

    db.structures.find({"some query that I do no know here"}: {
                 "Some Country", 
                 "Some City", 
                 "Some Building", 
                 "Some Floor"
              });

此查询将从上面 return json 对象,但它在集合中是对象:

"structure":{  
        "country":{  
           "name":"Some Country"
        },
        "city":{  
           "name":"Some City"
        },
        "building":{  
           "name":"Some Building"
        },
        "floor":{  
           "name":"Some Floor"
        }
   }

它将被 return 编辑,因为它具有所有四个匹配项。

我不确定我是否完全理解您的需求... 要搜索与您的 4 个值匹配的数据,请求应如下所示:

db.structures.find({
      "country.name":"Some Country", 
      "city.name":"Some City", 
      "building.name":"Some Building", 
      "floor.name":"Some Floor"
});

这是我想出的解决方案。

db.structures.findOne({$or:
                  [
                  {$and:[
                    {"country.name": "Some Country"},
                    {"city.name": "Some City"},
                    {"building.name": "Some Building"},
                    {"floor.name": "Some Floor"}]
                   },
                  {$and:[
                    {"country.name": "Some Country"},
                    {"city.name": "Some City"},
                    {"building.name": "Some Building"},
                    {"floor.name": ""}]
                  },
                  {$and:[
                    {"country.name": "Some Country"},
                    {"city.name": "Some City"},
                    {"building.name": ""},
                    {"floor.name": ""}]
                  },
                  {$and:[
                    {"country.name": "Some Country"},
                    {"city.name": ""},
                    {"building.name": ""},
                    {"floor.name": ""}]
                  }]
              });