mongodb basics - embedded document related

    The value of a field in mongodb can be a basic data type or a document type. In this case, if you want to query in the embedded document, you may need to index the fields of the embedded document. Listed below are some common operations on embedded documents.

    1. Indexing a single field of the embedded document

// Suppose a single document structure is as follows
{
  "_id": ObjectId("570c04a4ad233577f97dc459"),
  "score": 1034,
  "location": { state: "NY", city: "New York" }
}
// Index the state field of location
db.records.createIndex( { "location.state": 1 } )
// Both queries can use the state index
db.records.find( { "location.state": "CA" } )
db.records.find( { "location.city": "Albany", "location.state": "NY" } )

    2. Embedded document exact match query The basic syntax is: fieldName: {field1: <value>,...}, the returned result of this query satisfies: the embedded document only contains the queried fields, and the embedded document fields correspond to The values ​​of the inline document match exactly, and the order of the fields in the embedded document is the same as the order of the fields in the query.

// check sentence
db.bios.find( { name: { first: "Yukihiro", last: "Matsumoto" } } )


// The following two will not be matched. One is that the number of fields is inconsistent, and the other is that the order of fields is inconsistent
{
   first: "Yukihiro",
   aka: "Matz",
   last: "Matsumoto"
}

{
   last: "Matsumoto",
   first: "Yukihiro"
}

    3. Partial field query of embedded document The above exact matching is too strict, so partial field query is used, that is, as long as the queried field and value match, it will be returned, regardless of the order of the query fields and the number of fields in the embedded document. number.

// Embedded document part field query
db.bios.find( { "name.first": "Yukihiro", "name.last": "Matsumoto" } )

// The following two structures can also be queried
{
  first: "Yukihiro",
  aka: "Matz",
  last: "Matsumoto"
}

{
  last: "Matsumoto",
  first: "Yukihiro"
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326525562&siteId=291194637