Mongodb uses the cursor returned by the find query to see if it can traverse the new records added to the data table after the query is executed (the records are more and the query time is longer, and the query is not finished yet at this time).
Thread A uses find to query the data table user to return the cursor and traverse the data record at time t1.
Thread B uses insert to insert a record into data table user at time t2.
Thread B completes execution at time t3.
Thread A completes execution at time t4.
Time: t1 < t2 < t3 < t4
Q: Can Thread A query the new records added by Thread B?
This is a very good question. Simply speaking, MongoDB does not guarantee whether the result contains new documents, because it involves multiple documents, even documents that may be inserted in the future. In the traditional database, it is possible to read the newly inserted value. This abnormal situation is called Phantom. The isolation level that can satisfy this is the highest serializable level, that is to say, in the example, the read-once-write two groups of operations look like one after the other. The implementation cost of lock mechanism is also very high and its performance is relatively poor. SeeThis paper. Returning to MongoDB, MongoDB takes documents as a unit, which can ensure document-level isolation, but does not guarantee isolation (independence) of operations among multiple documents, and therefore does not support transactions, in return for high performance.
@huanduYou’re right, you used it in the test.
find().batchSize(2)Change to read 2 documents per batch, and you will find that you can read the newly added documents. DefaultbatchSizeIn the shell is 20, may not be easy to observe. Don’t use batchSize(1), because it is equal to limit () for historical reasons.