Comparing document fields

advertisements

Let's say I have this document structure:

{
    "user": "John Doe",
    "data": [1, 3, 2, 4, 1, 3],
    "data_version": 1
}

Can I query by data field in such a way so I could match all documents that match at least N values inside the array, at the same position?

So for example, in those data fields:

1, 3, 4, 2, 5, 1, 5
2, 5, 1, 4, 2, 3, 5
1, 3, 2, 5, 5, 4, 2
5, 2, 4, 1, 2, 2, 3

Searching for

1, 3, 3, 1, 5, 4, 3

with N minimum limit being 3, I'd get the 1st and 3rd document, but raising N to 4, I'd get only the 3rd document.


You will need to iterate over your collection. Something similar to the following should work:

var N = 3;
var query = [1,3,3,1,5,4,3];
db.users.find().forEach(function(entry) {
    var similarity = 0;
    for (i = 0; i < entry.data.length; i++) {
        if (entry.data[i] === query[i]) { similarity++; }
    }
    if (similarity > N) { print(entry); }
});

Does this help?