【问题标题】:In MongoDB how to find documents where property is object but not Array在 MongoDB 中如何查找属性是对象而不是数组的文档
【发布时间】:2019-08-10 16:11:53
【问题描述】:

我有集合users,其中每个都包含属性gyms,例如:

{
    "_id" : ObjectId("aaaaa"),
    "firstName" : "first",
    "lastName" : "second",
    "email" : "aaa@aaaa",
    "password" : "aaaaa",
    "gyms" : [
        {
            "name" : "aaaaaa",
            "address" : "aaaaaaaaaaaaa"
        }
    ]
}

但是,当我运行 db.users.aggregate(..) 时,我得到:

exception: Value at end of $unwind field path '$gyms' must be an Array, but is a Object

似乎有些用户文档包含gym:{} 或根本没有gym 而不是数组。我需要找到这些文件,我该怎么做?

编辑:

我运行的聚合命令:

db.users.aggregate({ $unwind: "$gyms" }, { $match: { "gyms.address": { $exists: true } } } )

【问题讨论】:

标签: mongodb


【解决方案1】:

使用{$type: "object"} 也会为您提供包含带有数组的文档的结果。因此,要检查纯对象,只需添加一个额外的检查以确保丢弃数组,即obj.0.key: {$exists: false}

在你的情况下,

db.users.find({"gyms": {$type: "object"}, "gyms.0.name": {$exists: false}}).map(function(u) {
    // modify u.gyms to your satisfaction
    db.conversations.save(c);
})

【讨论】:

    【解决方案2】:

    试试这个可能对你也有帮助

    db.users.aggregate([{
      "$match": {
          "$nor": [{
              "gyms": {
                  "$exists": false
              }
          }, {
              "gyms": {
                  "$size": 0
              }
          }, {
              "gyms": {
                  "$size": 1
              }
          }]
      }
     }, {
      "$unwind": "$gyms"
    }]).pretty()
    

    【讨论】:

      【解决方案3】:

      试试这样的:

      > db.test.drop()
      > db.test.insert({ "x" : ["an array"] })
      > db.test.insert({ "x" : { "type" : "object" } })
      > db.test.find({ "x" : { "$type" : 3 } })
      { "x" : { "type" : "object" } }
      

      【讨论】:

      • 问题是 $type: 3 对于对象和包含对象的数组的计算结果都为 true。因此,如果您添加了{ "x" : [{ "type" : "object" }] },它将无法正常工作
      猜你喜欢
      • 2015-01-20
      • 2020-04-14
      • 1970-01-01
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 2023-02-03
      • 1970-01-01
      • 2017-03-01
      相关资源
      最近更新 更多