Query in mongoose

Keywords: Javascript Mongoose less JSON MongoDB

find()

Model.find(filter[, projection][, options][, callback])

Parameter 1: filter

The query condition uses the format of JSON document, and the syntax of JSON document follows MongoDB shell The same is true.

{ field1: value1, field2: { operator: value2 } ... }

1. Find all

Model.find()
Model.find({})

2. Accurate search

Model.find({author:'dora'})

3. use Operator

Contrast correlation operator

Symbol describe
$eq Equal to specified value
$ne Not equal to specified value
$gt Greater than specified
$gte Greater than or equal to the specified value
$lt Less than the specified value
$lte Less than or equal to the specified value
$in Matches any of the values specified in the query array
$nin Does not match any of the values specified in the query array
Model.find({ age: { $in: [16, 18]} })

Returns all document s with an age field equal to 16 or 18.

Logical correlation operator

Symbol describe
$and Satisfies all conditions specified in the array
$nor All conditions specified in the array are not met
$or Satisfies one of the conditions specified in the array
$not Reverses the query and returns documents that do not meet the specified criteria
// Related grammar
{$and:[ {expression1},{expression2}, ... ,{expressionN} ]}
{$nor:[ {expression1},{expression2}, ... ,{expressionN} ]}
{$or:[ {expression1},{expression2}, ... ,{expressionN} ]}
{field: { $not: { <operator-expression> }}}

Comparisons in logical operators include cases where fields do not exist.

Model.find( { age: { $not: { $lte: 16 }}})
// Return documents with age field greater than 16 or without age field

Field related operators

Symbol describe
$exists Match document with specified field {field: {$exists: < Boolean >}}}
$type Return the document whose field belongs to the specified type {field: {$type: < bson type >}}}

4. Finding nested object fields

The data are as follows

{
  name: { first: "dora", last: "wang" }
}

Exact match, the order and field must be consistent.

Model.find({ name: { last: "wang", first: "dora" } })
// [] data not found

Using point syntax, you can match nested fields, where field names must be enclosed in quotation marks.

Model.find({ 'name.last': 'wang' })

5. Finding array fields

Symbol describe
$all Matches array fields that contain all conditions specified in the query array
$elemMatch Matches a value in an array field that meets all conditions specified in $elemMatch
$size Match the document whose length of array field is the same as the specified size

The data are as follows

{ year: [ 2018, 2019 ] }
{ year: [ 2017, 2019, 2020 ] }
{ year: [ 2016, 2020 ] }

Find at least one value in an array

You can use the exact lookup method {field: value}

Model.find({ year: 2019 });
// { "_id" : ..., "year" : [ 2018, 2019 ] }
// { "_id" : ..., "year" : [ 2017, 2019, 2020 ] }

Find multiple values in an array

Use $all to find document s that exist in 2019 and 2020 at the same time

Model.find({ year: { $all: [ 2019, 2020 ] } });
// { "_id" : ..., "year" : [ 2017, 2019, 2020 ] }

Operator combination query

Operators can be used for filtering, {< field >: {operator: value}}, such as $in

Model.find({ year: { $in: [ 2018, 2020 ] } });
// { "_id" : ..., "year" : [ 2018, 2019 ] }
// { "_id" : ..., "year" : [ 2017, 2019, 2020 ] }

Use operator combination query {< field >: {operator1: value1, operator2: Value2}}

Model.find({ year: { $gt: 2019, $lt: 2018 } });
// { "_id" : ..., "year" : [ 2017, 2019, 2020 ] }
// { "_id" : ..., "year" : [ 2016, 2020 ] }

The array field contains elements that meet the query criteria. Different elements can meet the criteria respectively or the same element can meet all the criteria. For example, in the above example, one value meets the criteria greater than 2019 and the other meets the criteria less than 2018.

$elemMatch single field value meets all query criteria

$elemMatch Find values in array fields that satisfy all conditions at the same time document.

{field: { $elemMatch: { <query1>, <query2>, ... }}}

Model.find({ year: { $elemMatch: { $gt: 2016, $lt: 2018 } } })
// { "_id" : ..., "year" : [ 2017, 2019, 2020 ] }

Array subscript query

Model.find({ 'year.1': { $gt: 2019 } })
// { "_id" : ..., "year" : [ 2016, 2020 ] }

The second value of array year is greater than 2019.

6. Finding array objects

The data are as follows

{author: [{name: "dora", age: 18 },{name: "wang", age: 16 }]}

Exact query

Exact match, the order and field must be consistent.

Model.find({ author: { name: "dora", age: 18 } })

Point syntax query

Model.find({ 'author.age': { $gte: 18 } })

$elemMatch meets all query conditions at the same time

Model.find({ "author": {$elemMatch: {name: 'dora', age:{ $lt: 18 }}})
// []

Parameter 2: Project

Specify which document fields (also known as query projections) to include or exclude. You must specify include or exclude at the same time. You can't specify mixed fields, except for "_id".

There are two ways to specify in mongoose: string and object.

When the string is specified, a - sign is added before the excluded field. Only the segment name is included.

Model.find({},'age');
Model.find({},'-name');

When object form is specified, 1 is included and 0 is excluded.

Model.find({}, { age: 1 });
Model.find({}, { name: 0 });

Use the select() method to define

Model.find().select('name age');
Model.find().select({ name: 0 });

Parameter 3: options

// Three ways to achieve
Model.find(filter,null,options)
Model.find(filter).setOptions(options)
Model.find(filter).<option>(xxx)

options See official documentation for options Query.prototype.setOptions().

  • sort: according to Sort rule Sort according to the given field. The value can be asc, desc, ascending, descending, 1, and -1.
  • limit: Specifies the maximum number of returned results
  • skip: Specify the number of documents to skip
  • lean: Return to normal js Object, not Mongoose Documents. Recommended not required mongoose It is better to use this method to convert the data returned to the front end after special processing js Object.
// sort two ways to specify sorting
Model.find().sort('age -name'); // String has - for descending
Model.find().sort({age:'asc', name:-1});

When sort and limit are used at the same time, the order of calls is not important. The data returned is sorted first and then limited.

// Same effect
Model.find().limit(2).sort('age');
Model.find().sort('age').limit(2);

Parameter 4: callback

afferent

In Mongoose, the format of all the queries that are passed in the callback is in the form of callback(error, result). If there is an error, the error is the error information and the result is null; if the query is successful, the error is null and the result is the query result. The structural form of the query result is different according to the different query methods.

The query result of the find() method is an array. Even if no content is queried, an empty array of [] will be returned.

No pass

When no callback is passed in, the Query method returns a Query instance, which inherits the Query prototype All methods on, so the returned instance can chain call other methods to form a query chain.

let query = Model.find({ name: 'Dora' });

query.select('name age -_id');

When the query method does not pass in the callback function, there are two ways to obtain the query data:

1. exec()

Use the exec() method of the query instance to execute the query, that is, at the end of the chain syntax, get the query data through the incoming call.

// Same effect
Model.find(
  { name: /Dora/, age: { $gte: 16, $lt: 18 } },
  'name age -_id',
  { limit: 2, sort: 'age' },
  (err,res)=>{
    if (err) return handleError(err);
    console.log(res);
  }
});

let query = Model.
  find({ name: /Dora/ }).
  where('age').gte(16).lt(18).
  select('name age -_id').
  limit(2).sort('age');

  query.exec((err, res)=> {
    if (err) return handleError(err);
    console.log(res);
  });

2. then()

Use the then() method of the query instance to treat the query chain as promise.

query.then(
  (res) => {console.log(res)},
  (err) => {console.log(err)}
);

Use async / await to get the query results.

let res = await query;
console.log(res);

findOne()

Model.findOne(conditions[, projection][, options][, callback])

conditions

If the query condition is "Ou id", findById() is recommended.

Limited options

Not all options are available, so when chaining methods on a Query prototype, only available methods can be called. Reference resources Query.prototype.setOptions().

Result query result

  • The format of the returned data is in the form of {} objects.
  • If more than one data meets the query criteria, only the first one will be returned.
  • The query conditions are {}, null or undefined, and any data will be returned.
  • No data meets the query criteria, result returns null.

findById()

Model.findById(id[, projection][, options][, callback])

id

Model.findById(id) is equivalent to model. Findone ({u id: ID}).

-- from the official

The difference is when the ID is undefined. findOne({u id: undefined}) is equivalent to findOne({}), which returns any data. And findById(undefined) is equivalent to findOne({﹣ u id: null}), which returns null.

The test result is findone ({u id: undefined}) and still returns null. Therefore, it may also be a problem with mongoose version, but even if the data returns normally, it is still recommended to use findById() for ﹐ ID query.

Result query result

  • The format of the returned data is in the form of {} objects.
  • id is undefined or null, and result returns null.
  • No data that meets the query criteria, result returns null.

Posted by lplatz on Thu, 14 Nov 2019 22:29:05 -0800