java - 蒙戈 : $type is not working in mongo find query

标签 java spring mongodb spring-boot

我的 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 }}) 返回两种类型的文档。

问题是,为我提供所有旧格式文档的查询是什么?

最佳答案

根据$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)" } );

关于java - 蒙戈 : $type is not working in mongo find query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42003863/

相关文章:

java - 当 setMaximumSize() 和 setPreferedSize() 不起作用时,如何对 JComponent 设置硬限制?

java - 如何将参数传递给 JsonSerializer?

java - 使用 RestTemplate 解析本地 JSON 文件

java - 查询从 mongoDB 获取结果

c++ - 如何为其构造函数采用右值的类声明变量?

java - 以不区分大小写的方式将 List<String> 转换为 Set-Java 6

java - 即使在构建路径中使用 ojdbc14.jar,Class.forName ("oracle.jdbc.driver.OracleDriver") 也会获取 ClassNotFoundException

java - EhCache @Cacheable 同步时抛出异常

linux - mongodb 无法从 mongo.conf 开始

java - Spring boot + tomcat 8.5 + mongoDB,AsyncRequestTimeoutException