1

So I have a mongo database with collections that have fields set to a type of array.

{
    "_id" : ObjectId("kdsfisdasg924837529dsfhk"),
    "myArr" : [ 
        123456
    ]
}

I'm looking to query this collection and find all documents, that do not have the elements in myArr set to a data type of long. I've been digging around, and I haven't found anything referencing a solution. I was trying something like: db.myCollection.find({myArr: {$not: {$type: "long"}}},{myArr:1, _id: 0})

If i pass .count() to it, it returns a large number of documents. Almost the entire collection's document count, which I know is incorrect. I'm guessing I'm using $not incorrectly. Is my syntax wrong? is there a different approach to solving this?

UPDATE

I believe I have solved the problem of finding the documents that have arrays without elements of the type long using: db.myCollection.find({myArr: {$elemMatch: {$not: {$type: "long"}}}}, {myArr:1, _id: 0}). How would one go about recasting or changing all those element's types to long?

For Refernce

Im getting pretty close. I believe I can modify this function I wrote to iterate over the array thats within the documents returned with the above function.

db.myCollection.find({myArr: {$elemMatch: {$not: {$type: 18}}}}).forEach(function(myDoc){
    for(var i =0; i < myDoc.myArr.length; i++){
        print(typeof myDoc.myArr[i]);
    }
});
mahbad
  • 149
  • 1
  • 2
  • 19
  • I've tried anding in `$exists` and `$not: $type: "undefined"` as well, but it returned the same `count()` – mahbad Jul 14 '17 at 15:31
  • I believe I found my solution. looks like i needed $elemMatch as follows, to iterate over the array elements: `db.myCollection.find({myArr: {$elemMatch: {$not: {$type: "long"}}}}, {myArr:1, _id: 0}).count()` – mahbad Jul 14 '17 at 15:37

1 Answers1

0

WHA! Got it! Thanks to Simone's and GatesVP's answer here

db.myCollection.find({myArr: {$elemMatch: {$not: {$type: 18}}}}).forEach(function(myDoc){
    for(var i =0; i < myDoc.myArr.length; i++){
        myDoc.myArr[i] = NumberLong(myDoc.myArr[i]);
        db.transactions.save(myDoc);
    }
});

I double checked by using MongoDB's compass GUI client and it shows all instances of myArr now contain nothing but long values in its elements. I also removed the $not logic in the previous find in the CLI client to make sure the data's value was preserved. looking good. Also printed the json for the last 3 results of that find command to take a peek inside each of the docs at how it was structured.

db.myCollection.find({myArr: {$elemMatch: {$type: 18}}}).sort({$natural: -1}).limit(3).forEach(printjson);
mahbad
  • 149
  • 1
  • 2
  • 19