有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java mongo:$type在mongo查找查询中不起作用

我的mongo文档如下所示:

{
    "_id" : ObjectId(abcd),
    "ratingComment" : {
        "_id" : NumberLong(1000),
        "comment" : "Test comment"
    }
}

我想将ratingComment字段转换为数组类型字段。所以我做了这个:

db.getCollection('ratingsAndReview').find({}).forEach(function(doc){doc.ratingComment=[doc.ratingComment];db.ratingsAndReview.save(doc);})

在这个查询之后,我注意到一些文档仍然具有旧的结构,并且ratingComment字段不是数组

现在它们是上述结构和以下结构的混合体:

{
    "_id" : ObjectId(abcd),
    "ratingComment" : [
        {
            "_id" : NumberLong(1000),
            "comment" : "Test comment"
        }
    ]
}

然后,我想检索所有包含reviewComment:{$type:3}的文档,但是这个查询db.ratingsAndReview.find({ratingComment:{$type:3}})返回这两种类型的文档

问题是,什么样的查询会给我提供所有旧格式的文档


共 (2) 个答案

  1. # 1 楼答案

    根据$type的文档

    Arrays

    When applied to arrays, $type matches any inner element that is of the specified type. Without projection this means that the entire array will match if any element has the right type. With projection, the results will include just those elements of the requested type.

    所以它基本上不检查数组字段的类型,而是检查数组字段中值的类型,因为数组中有对象,所以它也会返回包含数组字段的文档

    你可以试试

    db.ratingsAndReview.find({ratingComment:{$not:{$type:4}}})
    

    或者在$type文档示例中

    db.ratingsAndReview.find( { $where : "!Array.isArray(this.ratingComment)" } );
    
  2. # 2 楼答案

    尝试使用dot notation查询,通过从零开始的索引位置指定或访问数组的元素,如下所示:

    db.ratingsAndReview.find({ "ratingComment.0": { "$exists": false } })
    

    这将查询集合中ratingComment字段不是数组的文档,因为它没有任何元素作为数组