Puede consultar datos almacenados en MongoDB Atlas directamente desde el código de su aplicación cliente mediante el SDK web de Realm. Cliente MongoDB con la API de consulta. Atlas App Services proporciona reglas de acceso a datos en colecciones para recuperar resultados de forma segura según el usuario conectado o el contenido de cada documento.
Las siguientes acciones le permiten consultar un clúster MongoDB Atlas vinculado desde una aplicación web mediante el SDK web de Realm.
Nota
Cada operación descrita en esta página utiliza una consulta para buscar coincidencias en determinados documentos de la colección en la que se ejecuta la operación. Cuando un filtro busca coincidencias en varios documentos de una colección, estos se devuelven en un orden indeterminado a menos que se especifique un parámetro de ordenación. Esto significa que si no se especifica una ordenación para los... findOne(), o, updateOne() deleteOne() su operación podría coincidir con cualquier documento que coincida con la consulta. Para más información sobre la ordenación, consulte cursor.sort().
Requisitos previos
Antes de hacer query MongoDB desde tu aplicación web, debes configurar el acceso a los datos de MongoDB en tu App Services App. Para aprender a configurar tu aplicación backend para permitir que el SDK de Realm consulte Atlas, consulta Configurar el acceso a los datos de MongoDB en la documentación de App Services.
Configurar el proyecto
Configurar el proyecto
Follow the steps in the Install Realm for Web guide.
Vincula un clúster de servicio de MongoDB Atlas
Sigue los pasos de la guía Enlazar una fuente de datos. Asigne a su servicio un nombre significativo; lo necesitará para conectarse al clúster utilizando el SDK de Realm.
Datos de ejemplo
Los ejemplos en esta página usan la siguiente colección MongoDB que describe varias plantas a la venta en una cadena de tiendas de plantas:
{ _id: ObjectId("5f87976b7b800b285345a8b4"), name: "venus flytrap", sunlight: "full", color: "white", type: "perennial", _partition: "Store 42", }, { _id: ObjectId("5f87976b7b800b285345a8b5"), name: "sweet basil", sunlight: "partial", color: "green", type: "annual", _partition: "Store 42", }, { _id: ObjectId("5f87976b7b800b285345a8b6"), name: "thai basil", sunlight: "partial", color: "green", type: "perennial", _partition: "Store 42", }, { _id: ObjectId("5f87976b7b800b285345a8b7"), name: "helianthus", sunlight: "full", color: "yellow", type: "annual", _partition: "Store 42", }, { _id: ObjectId("5f87976b7b800b285345a8b8"), name: "petunia", sunlight: "full", color: "purple", type: "annual", _partition: "Store 47", },
Crear documentos
Estos fragmentos de código muestran cómo insertar uno o más documentos en una colección de MongoDB desde una aplicación web. Las operaciones de inserción toman uno o más documentos para agregarlos a MongoDB como argumento y devuelven una Promesa. que se resuelve en un objeto que contiene los resultados de la ejecución de la operación.
Inserta un solo documento
You can insert a single document by calling collection.insertOne().
The following snippet inserts a single document describing a "lily of the valley" plant into a collection of documents that describe plants for sale in a group of stores:
const result = await plants.insertOne({ name: "lily of the valley", sunlight: "full", color: "white", type: "perennial", _partition: "Store 47", }); console.log(result);
Running this snippet produces output resembling the following:
{ insertedId: ObjectId("5f879f83fc9013565c23360e") }
Inserta varios documentos
Puede insertar varios documentos al mismo tiempo utilizando collection.insertMany().
El siguiente fragmento inserta tres documentos que describen plantas en una colección de documentos que describen plantas en venta en un grupo de tiendas:
const result = await plants.insertMany([ { name: "rhubarb", sunlight: "full", color: "red", type: "perennial", _partition: "Store 47", }, { name: "wisteria lilac", sunlight: "partial", color: "purple", type: "perennial", _partition: "Store 42", }, { name: "daffodil", sunlight: "full", color: "yellow", type: "perennial", _partition: "Store 42", }, ]); console.log(result);
Running this snippet produces output resembling the following:
{ insertedIds: [ ObjectId("5f87a0defc9013565c233611"), ObjectId("5f87a0defc9013565c233612"), ObjectId("5f87a0defc9013565c233613"), ], }
Lea los documentos
Estos fragmentos de código muestran cómo leer datos almacenados en una colección de MongoDB desde una aplicación móvil. Las operaciones de lectura utilizan filtros de consulta para especificar qué documentos devolver de la base de datos. Devuelven una promesa que se resuelve en uno de los siguientes: un único documento coincidente (en el caso findOne() de), un valor numérico (en el caso count() de) o una matriz de documentos coincidentes (en el caso find() de).
Find a Single Document
Puede encontrar un solo documento utilizando collection.findOne().
El siguiente snippet encuentra el documento que describe las venus atrapamoscas en la colección de documentos que describe plantas en venta en grupos de tiendas:
const venusFlytrap = await plants.findOne({ name: "venus flytrap" }); console.log("venusFlytrap", venusFlytrap);
Running this snippet produces output resembling the following:
{ _id: ObjectId("5f87976b7b800b285345a8b4"), name: "venus flytrap", sunlight: "full", color: "white", type: "perennial", _partition: "Store 42", }
Encuentra varios documentos
You can find multiple documents using collection.find().
El siguiente snippet encuentra todos los documentos en una colección de documentos que describen plantas a la venta en un grupo de almacenes que contienen un campo llamado type con un valor de "perenne":
const perennials = await plants.find({ type: "perennial" }); console.log("perennials", perennials);
Running this snippet produces output resembling the following:
[ { _id: ObjectId("5f87976b7b800b285345a8b4"), name: "venus flytrap", sunlight: "full", color: "white", type: "perennial", _partition: "Store 42", }, { _id: ObjectId("5f87976b7b800b285345a8b6"), name: "thai basil", sunlight: "partial", color: "green", type: "perennial", _partition: "Store 42", }, ]
Contar documentos en la colección
Puedes contar los documentos de una colección usando collection.count(). Puedes especificar una consulta opcional para determinar qué documentos contar. Si no especificas una consulta, la acción cuenta todos los documentos de la colección.
El siguiente fragmento cuenta la cantidad de documentos en una colección de documentos que describen plantas en venta en un grupo de tiendas:
const numPlants = await plants.count(); console.log(`There are ${numPlants} plants in the collection`);
Running this snippet produces output resembling the following:
"There are 5 plants in the collection"
Update Documents
These code snippets demonstrate how to update data stored in a MongoDB collection from a mobile application. Update operations use queries to specify which documents to update and update operators to describe how to mutate documents that match the query. Update operations return a Promise that resolves to an object that contains the results of the execution of the operation.
Actualiza un solo documento
You can update a single document using collection.updateOne().
The following snippet updates a single document in a collection of documents that describe plants for sale in a group of stores. This operation queries for a document where the name field contains the value "petunia" and changes the value of the first matched document's sunlight field to "partial":
const result = await plants.updateOne( { name: "petunia" }, { $set: { sunlight: "partial" } } ); console.log(result);
Running this snippet produces output resembling the following:
{ matchedCount: 1, modifiedCount: 1 }
Actualiza varios documentos
Puedes actualizar un único documento usando collection.updateMany().
El siguiente fragmento actualiza varios documentos de una colección que describen plantas en venta en un grupo de tiendas. Esta operación busca documentos cuyo _partition campo contenga el valor "Tienda 42" y cambia el valor del _partition campo de cada documento coincidente a "Tienda 51":
const result = await plants.updateMany( { _partition: "Store 42" }, { $set: { _partition: "Store 51" } } ); console.log(result);
Running this snippet produces output resembling the following:
{ matchedCount: 4, modifiedCount: 4 }
Realizar inserción de documentos
Si una operación de actualización no coincide con ningún documento en la colección, puedes insertar automáticamente un nuevo documento en la colección que coincida con la query de actualización configurando la opción upsert en true.
El siguiente fragmento actualiza un documento de una colección que describe plantas en venta en un grupo de tiendas o inserta un nuevo documento si ningún documento coincide con la consulta. Esta operación busca documentos donde:
el campo
sunlighttiene un valor de "completo"El campo
typetiene un valor de "perenne"the
colorfield has a value of "green"el campo
_partitiontiene el valor "Store 47".
Because this snippet sets the upsert option to true, if no document matches the query, MongoDB creates a new document that includes both the query and specified updates:
const result = await plants.updateOne( { sunlight: "full", type: "perennial", color: "green", _partition: "Store 47", }, { $set: { name: "super sweet basil" } }, { upsert: true } ); console.log(result);
Running this snippet produces output resembling the following:
{ matchedCount: 0, modifiedCount: 0, upsertedId: ObjectId("5f1f63055512f2cb67f460a3"), }
Delete Documents
Estos snippets demuestran cómo borrar documentos almacenados en una colección de MongoDB desde una aplicación móvil. Las operaciones de borrar utilizan una query para especificar qué documentos borrar y devuelven una Promise que se resuelve en un objeto que contiene los resultados de la ejecución de la operación.
Borrar un único documento
Puedes eliminar un solo documento de una colección utilizando collection.deleteOne().
The following snippet deletes one document in a collection of documents that describe plants for sale in a group of stores. This operation queries for a document where the color field has a value of "green" and deletes the first document that matches the query:
const result = await plants.deleteOne({ color: "green" }); console.log(result);
Running this snippet produces output resembling the following:
{ deletedCount: 1 }
Borra varios documentos
Puede borrar varios elementos de una colección usando collection.deleteMany().
The following snippet deletes all documents for plants that are in "Store 42" in a collection of documents that describe plants for sale in a group of stores:
const result = await plants.deleteMany({ _partition: "Store 42", }); console.log(result);
Running this snippet produces output resembling the following:
{ deletedCount: 4 }
Esté atento a los cambios
Puedes llamar a collection.watch() para suscribirte a eventos de notificación en tiempo real cada vez que se añade, modifica o elimina un documento de la colección. Cada notificación especifica qué documento cambió, cómo cambió y el documento completo después de la operación que causó el evento.
Importante
Serverless Limitations
No puedes observar cambios si la fuente de datos es una instancia sin servidor de Atlas. El servidor sin servidor de MongoDB actualmente no admite flujos de cambios, que se emplean en las colecciones monitoreadas para escuchar cambios.
Atlas App Services uses MongoDB change streams on watched collections to listen for changes and broadcasts notifications to subscribed client applications. This is useful for cases where you want to know when something happened while a user is online. For example:
Rastrear la ubicación de una entrega
Obtén los puntajes y estadísticas más actualizados para un juego
Update a chat thread when a user sends a new message
Nota
collection.watch() devuelve un generador asincrónico que le permite extraer de forma asincrónica eventos de cambio para las operaciones a medida que ocurren.
Esté atento a los cambios en una colección
Para observar todos los cambios en una colección, llama a collection.watch() sin ningún argumento:
for await (const change of plants.watch()) { let breakAsyncIterator = false; // Later used to exit async iterator switch (change.operationType) { case "insert": { const { documentKey, fullDocument } = change; console.log(`new document: ${documentKey}`, fullDocument); breakAsyncIterator = true; break; } case "update": { const { documentKey, fullDocument } = change; console.log(`updated document: ${documentKey}`, fullDocument); breakAsyncIterator = true; break; } case "replace": { const { documentKey, fullDocument } = change; console.log(`replaced document: ${documentKey}`, fullDocument); breakAsyncIterator = true; break; } case "delete": { const { documentKey } = change; console.log(`deleted document: ${documentKey}`); breakAsyncIterator = true; break; } } if (breakAsyncIterator) break; // Exit async iterator }
Esté atento a los cambios en una colección con un filtro
To watch for specific changes in a collection, call collection.watch() with a query that specifies change event values to watch:
for await (const change of plants.watch({ filter: { operationType: "update", "fullDocument.type": "perennial", }, })) { // The change event will always represent a newly inserted perennial const { documentKey, fullDocument } = change; console.log(`new document: ${documentKey}`, fullDocument); break; // Exit async iterator }
Documentos agregados
Las operaciones de agregación procesan todos los documentos de una colección a través de una serie de etapas denominadas pipeline de agregación. La agregación te permite filtrar y transformar documentos, recopilar datos resumidos sobre grupos de documentos relacionados y otras operaciones complejas de datos.
Las operaciones de agregación aceptan una lista de etapas de agregación como entrada y devuelven una Promise que se resuelve en una colección de documentos procesados por la pipeline.
Agrega documentos a una colección
Puede ejecutar una canalización de agregación utilizando collection.aggregate().
The following snippet groups all documents in the plants collection by their type value and aggregates a count of the number of each type:
const result = await plants.aggregate([ { $group: { _id: "$type", total: { $sum: 1 }, }, }, { $sort: { _id: 1 } }, ]); console.log(result);
Running this snippet produces output resembling the following:
[ { _id: "annual", total: 3 }, { _id: "perennial", total: 2 }, ]
Etapas de agregación
Filtrar Documentos
Puedes usar la etapa $match para filtrar documentos según la sintaxis de queryestándar de MongoDB.
{ "$match": { "<Field Name>": <Query Expression>, ... } }
Ejemplo
El siguiente filtro de etapa $match filtra documentos para incluir solo aquellos donde el campo type tenga un valor igual a "perenne":
const perennials = await plants.aggregate([ { $match: { type: { $eq: "perennial" } } }, ]); console.log(perennials);
[ { "_id": ObjectId("5f87976b7b800b285345a8c4"), "_partition": "Store 42", "color": "white", "name": "venus flytrap", "sunlight": "full", "type": "perennial" }, { "_id": ObjectId("5f87976b7b800b285345a8c6"), "_partition": "Store 42", "color": "green", "name": "thai basil", "sunlight": "partial", "type": "perennial" }, { "_id": ObjectId("5f87a0dffc9013565c233612"), "_partition": "Store 42", "color": "purple", "name": "wisteria lilac", "sunlight": "partial", "type": "perennial" }, { "_id": ObjectId("5f87a0dffc9013565c233613"), "_partition": "Store 42", "color": "yellow", "name": "daffodil", "sunlight": "full", "type": "perennial" }, { "_id": ObjectId("5f1f63055512f2cb67f460a3"), "_partition": "Store 47", "color": "green", "name": "sweet basil", "sunlight": "full", "type": "perennial" } ]
Documentos de grupo
You can use the $group stage to aggregate summary data for one or more documents. MongoDB groups documents based on the expression defined in the _id field of the $group stage. You can reference a specific document field by prefixing the field name with a $.
{ "$group": { "_id": <Group By Expression>, "<Field Name>": <Aggregation Expression>, ... } }
Ejemplo
La siguiente etapa $group organiza los documentos por valor de su campo type y calcula la cantidad de documentos de plantas en los que cada valor único type aparece.
const result = await plants.aggregate([ { $group: { _id: "$type", numItems: { $sum: 1 }, }, }, { $sort: { _id: 1 } }, ]); console.log(result);
[ { _id: "annual", numItems: 1 }, { _id: "perennial", numItems: 5 }, ]
Paginación de documentos
Para paginar los resultados puedes utilizar consultas de agregación por rangos con los operadores $match, $sort, y $limit. Para obtener más información sobre cómo paginar documentos, consulta Uso de consultas por rango en la documentación de MongoDB Server.
Ejemplo
The following example paginates through a collection of documents in ascending order.
// Paginates through list of plants // in ascending order by plant name (A -> Z) async function paginateCollectionAscending( collection, nPerPage, startValue ) { const pipeline = [{ $sort: { name: 1 } }, { $limit: nPerPage }]; // If not starting from the beginning of the collection, // only match documents greater than the previous greatest value. if (startValue !== undefined) { pipeline.unshift({ $match: { name: { $gt: startValue }, }, }); } const results = await collection.aggregate(pipeline); return results; } // Number of results to show on each page const resultsPerPage = 3; const pageOneResults = await paginateCollectionAscending( plants, resultsPerPage ); const pageTwoStartValue = pageOneResults[pageOneResults.length - 1].name; const pageTwoResults = await paginateCollectionAscending( plants, resultsPerPage, pageTwoStartValue ); // ... can keep paginating for as many plants as there are in the collection
Campos del documento del proyecto
Puede usar la etapa $project para incluir u omitir campos específicos de los documentos o para calcular nuevos campos mediante operadores de agregación. Las proyecciones funcionan de dos maneras:
Incluya de forma explícita campos con un valor de 1. Esto tiene el efecto secundario de excluir, de forma implícita, todos los campos no especificados.
Implicitly exclude fields with a value of 0. This has the side-effect of implicitly including all unspecified fields.
Estos dos métodos de proyección son mutuamente excluyentes: si incluyes explícitamente campos, no puedes excluir explícitamente campos y viceversa.
Nota
The _id field is a special case: it is always included in every query unless explicitly specified otherwise. For this reason, you can exclude the _id field with a 0 value while simultaneously including other fields, like _partition, with a 1. Only the special case of exclusion of the _id field allows both exclusion and inclusion in one $project stage.
{ "$project": { "<Field Name>": <0 | 1 | Expression>, ... } }
Ejemplo
The following $project stage omits the _id field, includes the name field, and creates a new field named storeNumber. The storeNumber is generated using two aggregation operators:
$splitseparates the_partitionvalue into two string segments surrounding the space character. For example, the value "Store 42" split in this way returns an array with two elements: "Store" and "42".$arrayElemAtselects a specific element from an array based on the second argument. In this case, the value1selects the second element from the array generated by the$splitoperator since arrays index from0. For example, the value ["Store", "42"] passed to this operation would return a value of "42".
const result = await plants.aggregate([ { $project: { _id: 0, name: 1, storeNumber: { $arrayElemAt: [{ $split: ["$_partition", " "] }, 1], }, }, }, ]); console.log(result);
[ { "name": "venus flytrap", "storeNumber": "42" }, { "name": "thai basil", "storeNumber": "42" }, { "name": "helianthus", "storeNumber": "42" }, { "name": "wisteria lilac", "storeNumber": "42" }, { "name": "daffodil", "storeNumber": "42" }, { "name": "sweet basil", "storeNumber": "47" } ]
Agregar campos a los documentos
Puedes utilizar la etapa $addFields para añadir nuevos campos con valores calculados utilizando operadores de agregación.
{ $addFields: { <newField>: <expression>, ... } }
Nota
$addFields es similar a $project pero no te permite incluir ni omitir campos.
Ejemplo
The following $addFields stage creates a new field named storeNumber where the value is the output of two aggregate operators that transform the value of the _partition field.
const result = await plants.aggregate([ { $addFields: { storeNumber: { $arrayElemAt: [{ $split: ["$_partition", " "] }, 1], }, }, }, ]); console.log(result);
[ { "_id": ObjectId("5f87976b7b800b285345a8c4"), "_partition": "Store 42", "color": "white", "name": "venus flytrap", "storeNumber": "42", "sunlight": "full", "type": "perennial" }, { "_id": ObjectId("5f87976b7b800b285345a8c6"), "_partition": "Store 42", "color": "green", "name": "thai basil", "storeNumber": "42", "sunlight": "partial", "type": "perennial" }, { "_id": ObjectId("5f87976b7b800b285345a8c7"), "_partition": "Store 42", "color": "yellow", "name": "helianthus", "storeNumber": "42", "sunlight": "full", "type": "annual" }, { "_id": ObjectId("5f87a0dffc9013565c233612"), "_partition": "Store 42", "color": "purple", "name": "wisteria lilac", "storeNumber": "42", "sunlight": "partial", "type": "perennial" }, { "_id": ObjectId("5f87a0dffc9013565c233613"), "_partition": "Store 42", "color": "yellow", "name": "daffodil", "storeNumber": "42", "sunlight": "full", "type": "perennial" }, { "_id": ObjectId("5f1f63055512f2cb67f460a3"), "_partition": "Store 47", "color": "green", "name": "sweet basil", "storeNumber": "47", "sunlight": "full", "type": "perennial" } ]
Unwind Array Values
You can use the $unwind stage to transform a single document containing an array into multiple documents containing individual values from that array. When you unwind an array field, MongoDB copies each document once for each element of the array field but replaces the array value with the array element in each copy.
{ $unwind: { path: <Array Field Path>, includeArrayIndex: <string>, preserveNullAndEmptyArrays: <boolean> } }
Ejemplo
El siguiente ejemplo utiliza la etapa $unwind para la combinación type y color de cada objeto. La canalización de agregación consta de los siguientes pasos:
Use
$groupstage with$addToSetto create new documents for eachtypewith a new fieldcolorsthat contains an array of all the the colors for that flower type that occur in the collection.Utilice la etapa
$unwindpara crear documentos separados para cada combinación de tipo y color.Use
$sortstage to sort the results in alphabetical order.
const result = await plants.aggregate([ { $group: { _id: "$type", colors: { $addToSet: "$color" } } }, { $unwind: { path: "$colors" } }, { $sort: { _id: 1, colors: 1 } }, ]); console.log(result);
[ { "_id": "annual", "colors": "yellow" }, { "_id": "perennial", "colors": "green" }, { "_id": "perennial", "colors": "purple" }, { "_id": "perennial", "colors": "white" }, { "_id": "perennial", "colors": "yellow" }, ]