0

I have 2 cursors over a same mongodb collection, referencing 2 different subsets of documents. How can I determine the difference between the two, that is, elements in cursor #1 which are NOT in cursor #2 Thanks

var cursor1=collection1.find(...condition 1...);
var cursor2=collection2.find(...condition 2..., fields:{collection1index:1,});
var difference=...
haton
  • 1
  • 2
  • maybe send another query, just to get the difference? like cursor2-cursor1= find( condtion2 but not condition1)? – Takis Nov 14 '21 at 16:54
  • Hello Takis, thanks for the suggestion. Actually it is a little bit more complex because cursor2 is obtained from a .find on another collection. In this other collection, one of the fields is a reference to the first collection. I have edited the question. – haton Nov 14 '21 at 17:01
  • you still can do it, with aggregation `$match` and `$unionWith` see MongoDB documentation – Takis Nov 14 '21 at 17:21
  • Great. If I understand, you mean: convert the first cursor to an array, then apply a $nin condition to match the elements of the second cursor which are not in the first one. This should work indeed but it sounds inefficient: by converting the cursor to an array, we lose the fact that it is a cursor (unique values, possibly sorted) and we will match the elements by brute force. See what I mean? – haton Nov 14 '21 at 18:04
  • i mean something [like this](https://mongoplayground.net/p/KppdCNSsLKs) , use aggregation with `$unionWith` , but without saple data its so hard to know what you mean, for example what do you mean different? different in 1 field? in many? i think you just need to send 1 query to get the difference but create a condition to get it. – Takis Nov 14 '21 at 18:28
  • You can get an array from a cursor (`cursor.toArray()``). With two arrays you can find [How to get the difference between two arrays in JavaScript?](https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript). This can work fine if the amount of documents in the arrays are not too large. – prasad_ Nov 15 '21 at 03:20
  • My input is more like this: https://mongoplayground.net/p/Ujb5JoMHAFf Items in collection 2 bear a reference to an element in collection 1. I Want to find which elements in collection 1 are not referenced by any element in collection 2 (in this case the element with _id=3) – haton Nov 15 '21 at 21:24

0 Answers0