Definición
The in operator in MongoDB Search performs a search for an array of BSON number, date, boolean, objectId, uuid, or string values at the given path and returns documents where the value of the field equals any value in the specified array. If the field holds an array, then the in operator selects the documents whose field holds an array that contains at least one element that matches any value in the specified array.
Sintaxis
El operador in tiene la siguiente sintaxis:
{ $search: { "index": <index name>, // optional, defaults to "default" "in": { "path": "<field-to-search>", "score": <options>, "value": <single-or-array-of-values-to-search>, "doesNotAffect": "<facet-to-exclude>" | [<array-of-facets>] } } }
Campos
Campo | Tipo | Descripción | Necesidad |
|---|---|---|---|
| string o arreglo de strings | Requerido | |
| Objeto | Puntuación que se asigna a los resultados coincidentes con los términos de búsqueda. Utiliza una de las siguientes opciones para modificar la puntuación:
| Opcional |
| Requerido | ||
| string o arreglo de strings | Faceta o lista de facetas que se deben excluir del recálculo del recuento en función de esta query. El valor debe ser uno o más nombres de una faceta definida en | Opcional |
Ejemplos
The following examples use the in operator to query collections in the sample_analytics.customers collection. If you load the sample data on your cluster and create a MongoDB Search index named default that uses static mappings on the collection, you can run the following queries against the collections.
Índice de muestra
La definición de índice de muestra especifica las siguientes acciones para soportar consultas de operadores in en los campos indexados de la colección:
Indexe automáticamente todos los campos indexables dinámicos en la colección.
Indexa estáticamente el campo
namecomo el tipo token y convierte el texto del campo en minúsculas.
{ "mappings": { "index": "default", "dynamic": true, "fields": { "name": { "normalizer": "lowercase", "type": "token" } } } }
Para aprender a crear un índice de búsqueda de MongoDB, consulta Administrar índices de búsqueda de MongoDB.
Queries de muestra
The following query uses the in operator to search the birthdate field, which contains a single value, for customers who were born on given dates. The query uses the $project stage to:
Omitir el campo
_iden los resultados.Incluye solo los campos
nameybirthdateen los resultados.
1 db.customers.aggregate([ 2 { 3 "$search": { 4 "in": { 5 "path": "birthdate", 6 "value": [ISODate("1977-03-02T02:20:31.000+00:00"), ISODate("1977-03-01T00:00:00.000+00:00"), ISODate("1977-05-06T21:57:35.000+00:00")] 7 } 8 } 9 }, 10 { 11 "$project": { 12 "_id": 0, 13 "name": 1, 14 "birthdate": 1 15 } 16 } 17 ])
1 [ 2 { 3 name: 'Elizabeth Ray', 4 birthdate: ISODate("1977-03-02T02:20:31.000Z") 5 }, 6 { 7 name: 'Brad Cardenas', 8 birthdate: ISODate("1977-05-06T21:57:35.000Z") 9 } 10 ]
MongoDB Search devuelve dos documentos que coinciden con las fechas especificadas en la query.
The following query uses the in operator to query the accounts field, which contains an array of numbers, for customers with account numbers 371138, 371139, or 371140. The query uses the $project stage to:
Omitir el campo
_iden los resultados.Incluye solo los campos
nameyaccountsen los resultados.
1 db.customers.aggregate([ 2 { 3 "$search": { 4 "in": { 5 "path": "accounts", 6 "value": [371138, 371139, 371140] 7 } 8 } 9 }, 10 { 11 "$project": { 12 "_id": 0, 13 "name": 1, 14 "accounts": 1 15 } 16 } 17 ])
1 [ 2 { 3 name: 'Elizabeth Ray', 4 accounts: [ 371138, 324287, 276528, 332179, 422649, 387979 ] 5 } 6 ]
MongoDB Search sólo devuelve un documento que coincide con el número de cuenta 371138 especificado en la consulta.
The following query uses the text operator to query for customers whose first name is James in the name field. The query specifies preference using the in operator for customers associated with the given objectIds in the _id field. The query uses $limit stage to limit the output to 5 results and the $project stage to:
Incluye solo los campos
_idynameen los resultados.Agrega un campo llamado
scorea los resultados.
1 db.customers.aggregate([ 2 { 3 "$search": { 4 "compound": { 5 "must": [{ 6 "in": { 7 "path": "name", 8 "value": ["james sanchez", "jennifer lawrence"] 9 } 10 }], 11 "should": [{ 12 "in": { 13 "path": "_id", 14 "value": [ObjectId("5ca4bbcea2dd94ee58162a72"), ObjectId("5ca4bbcea2dd94ee58162a91")] 15 } 16 }] 17 } 18 } 19 }, 20 { 21 "$limit": 5 22 }, 23 { 24 "$project": { 25 "_id": 1, 26 "name": 1, 27 "score": { $meta: "searchScore" } 28 } 29 } 30 ])
1 [ 2 { 3 _id: ObjectId("5ca4bbcea2dd94ee58162a72"), 4 name: 'James Sanchez', 5 score: 2 6 }, 7 { 8 _id: ObjectId("5ca4bbcea2dd94ee58162a71"), 9 name: 'Jennifer Lawrence', 10 score: 1 11 } 12 ]
MongoDB Search devuelve documentos que contienen James Sanchez y Jennifer Lawrence en el campo name. MongoDB Search asigna una puntuación más alta al documento que contiene name: 'James Sanchez' porque coincide con el ObjectId especificado en la cláusula should.
faceta query
La siguiente query utiliza el operador in para buscar en el campo active, que contiene un valor booleano, para los clientes que están activos. La query devuelve el número de clientes activos cuya fecha de nacimiento se encuentra en los siguientes buckets:
1970-01-01, límite inferior inclusivo para este bucket
1980-01-01, límite superior exclusivo para el cubo de 1970-01-01 y límite inferior inclusivo para este cubo
1990-01-01, límite superior exclusivo para el cubo de 1980-01-01 y límite inferior inclusivo para este cubo
2000-01-01, límite superior exclusivo para el intervalo 1990-01-01
1 db.customers.aggregate([ 2 { 3 "$searchMeta": { 4 "facet": { 5 "operator": { 6 "in": { 7 "path": "active", 8 "value": null 9 } 10 }, 11 "facets": { 12 "birthdateFacet": { 13 "type": "date", 14 "path": "birthdate", 15 "boundaries": [ISODate("1970-01-01"), ISODate("1980-01-01"), ISODate("1990-01-01"), ISODate("2000-01-01")], 16 "default": "other" 17 } 18 } 19 } 20 } 21 } 22 ])
[ { count: { lowerBound: Long('1') }, facet: { birthdateFacet: { buckets: [ { _id: ISODate('1970-01-01T00:00:00.000Z'), count: Long('1') }, { _id: ISODate('1980-01-01T00:00:00.000Z'), count: Long('0') }, { _id: ISODate('1990-01-01T00:00:00.000Z'), count: Long('0') } ] } } } ]