Query records
Common Query
> Var cursor = dB. Things. Find ();
> While (cursor. hasnext () printjson (cursor. Next ());
The above example shows the cursor-style iterative output. The hasnext () function tells us whether there is any data. If so, you can call the next () function.
When we use JavaScript shell, we can use the JS features, and foreach can output the cursor. the following example uses foreach () for loop output: foreach () must define a function for each cursor element to call.
> DB. Things. Find (). foreach (printjson );
In MongoDB shell, we can also use the cursor as an array:
> Var cursor = dB. Things. Find ();
> Printjson (cursor [4]);
When using a cursor, pay attention to the memory usage, especially for large cursor objects, which may be output through iteration. the following example converts a cursor to a real array type:
> Var arr = dB. Things. Find (). toarray ();
> Arr [5];
Conditional Query
> DB. Things. Find ({name: "mongo"}). foreach (printjson );
> DB. Things. Find ({X: 4, Y: "ABC"}). foreach (printjson );
Returns a specific element.
> DB. Things. Find ({X: 4}, {J: true}). foreach (printjson );
Findone () syntax
Printjson (db. Things. findone ({name: "mongo "}));
Limit the number of result sets by using limit
> DB. Things. Find (). Limit (3 );
Modify record
> DB. Things. Update ({name: "mongo" },{$ set: {name: "mongo_new "}});
Delete record
> DB. Things. Remove ({name: "mongo_new "});