简体   繁体   中英

mongo : $type is not working in mongo find query

My mongo document looked like this:

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

I wanted to convert ratingComment field into an array type field. So I did this :

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

After this query I notice that some of the documents still have the old structure and ratingComment field is not an array.

So now they are mix of the above structure and the below one:

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

I, then, wanted to retrieve all the documents which have reviewComment:{$type:3} but this query db.ratingsAndReview.find({ratingComment:{$type:3}}) returns both type of documents.

The question is, what would be the query which gives me all the documents which are in old format ?

According to the documentation of $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.

so basically it doesn't check the type of the array field, it checks type of value inside array field, and since inside array there are objects it returns document containing array field also.

you can try something like

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

or as in $type documentation example

db.ratingsAndReview.find( { $where : "!Array.isArray(this.ratingComment)" } );

Try querying with the dot notation to specify or access an element of an array by the zero-based index position as:

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

This will query the collection for documents where the ratingComment field is not an array by virtue of the fact that it doesn't have any element as an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM