{"id":2762,"date":"2023-07-20T19:48:56","date_gmt":"2023-07-20T19:48:56","guid":{"rendered":"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/"},"modified":"2023-07-20T19:48:56","modified_gmt":"2023-07-20T19:48:56","slug":"mongodb-inserir-se-nao-existir","status":"publish","type":"post","link":"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/","title":{"rendered":"Mongodb: como inserir se n\u00e3o existir"},"content":{"rendered":"<p><\/p>\n<hr>\n<p><span style=\"color: #000000;\">Voc\u00ea pode usar a seguinte sintaxe para inserir um documento em uma cole\u00e7\u00e3o no MongoDB somente se ele ainda n\u00e3o existir:<\/span><\/p>\n<pre style=\"background-color: #ececec; font-size: 15px;\"> <strong>db.teams.update(\n\t{\n\t  team: 'Hornets'\n\t}, \n\t {\n\t  <span style=\"color: #3366ff;\">$setOnInsert<\/span> : {team: 'Hornets', points: '58', rebounds: '20'}\n\t },\n\t {upsert: <span style=\"color: #008000;\">true<\/span> }\n)\n<\/strong><\/pre>\n<p> <span style=\"color: #000000;\">Este c\u00f3digo espec\u00edfico verifica se o campo \u201cteam\u201d possui o valor \u201cHornets\u201d. Se esse valor existir, nada acontecer\u00e1.<\/span><\/p>\n<p> <span style=\"color: #000000;\">Por\u00e9m, caso este valor n\u00e3o exista ent\u00e3o ir\u00e1 inserir um documento com valores espec\u00edficos para os campos \u201cequipe\u201d, \u201cpontos\u201d e \u201crebotes\u201d.<\/span><\/p>\n<p> <span style=\"color: #000000;\">O exemplo a seguir mostra como usar essa sintaxe na pr\u00e1tica.<\/span><\/p>\n<h3> <span style=\"color: #000000;\"><strong>Exemplo: Inserir se n\u00e3o existir no MongoDB<\/strong><\/span><\/h3>\n<p> <span style=\"color: #000000;\">Digamos que temos uma cole\u00e7\u00e3o chamada<\/span> <span style=\"padding: 1px; border: 1px solid black;\">equipes<\/span> <span style=\"color: #000000;\">com os seguintes documentos:<\/span><\/p>\n<pre style=\"background-color: #ececec; font-size: 15px;\"> <strong>db.teams.insertOne({team: \" <span style=\"color: #ff0000;\">Mavs<\/span> \", points: 30, rebounds: 8})\ndb.teams.insertOne({team: \" <span style=\"color: #ff0000;\">Spurs<\/span> \", points: 35, rebounds: 12})\ndb.teams.insertOne({team: \" <span style=\"color: #ff0000;\">Rockets<\/span> \", points: 20, rebounds: 7})\ndb.teams.insertOne({team: \" <span style=\"color: #ff0000;\">Warriors<\/span> \", points: 25, rebounds: 5})\ndb.teams.insertOne({team: \" <span style=\"color: #ff0000;\">Cavs<\/span> \", points: 23, rebounds: 9})<\/strong><\/pre>\n<p> <span style=\"color: #000000;\"><span style=\"color: #000000;\">Digamos que usamos o seguinte c\u00f3digo para tentar inserir um documento para a equipe \u201cMavs\u201d:<\/span><\/span><\/p>\n<pre style=\"background-color: #ececec; font-size: 15px;\"> <strong>db.teams.update(\n\t{\n\t  team: 'Mavs'\n\t}, \n\t {\n\t  <span style=\"color: #3366ff;\">$setOnInsert<\/span> : {team: 'Mavs', points: '58', rebounds: '20'}\n\t },\n\t {upsert: <span style=\"color: #008000;\">true<\/span> }\n)<\/strong><\/pre>\n<p> <span style=\"color: #000000;\">O campo \u201cequipe\u201d j\u00e1 cont\u00e9m informa\u00e7\u00f5es dos \u201cMavs\u201d, nenhum dos documentos ser\u00e1 modificado.<\/span><\/p>\n<p> <span style=\"color: #000000;\">Por\u00e9m, digamos que usamos o seguinte c\u00f3digo para inserir um documento para a equipe &#8220;Hornets&#8221;:<\/span><\/p>\n<pre style=\"background-color: #ececec; font-size: 15px;\"> <strong>db.teams.update(\n\t{\n\t  team: 'Hornets'\n\t}, \n\t {\n\t  <span style=\"color: #3366ff;\">$setOnInsert<\/span> : {team: 'Hornets', points: '58', rebounds: '20'}\n\t },\n\t {upsert: <span style=\"color: #008000;\">true<\/span> }\n)<\/strong><\/pre>\n<p> <span style=\"color: #000000;\">Como o campo \u201ctime\u201d ainda n\u00e3o cont\u00e9m informa\u00e7\u00f5es dos \u201cHornets\u201d, um novo documento ser\u00e1 adicionado \u00e0 cole\u00e7\u00e3o com os valores que especificamos para cada campo.<\/span><\/p>\n<p> <span style=\"color: #000000;\">Esta \u00e9 a apar\u00eancia da cole\u00e7\u00e3o atualizada:<\/span><\/p>\n<pre style=\"background-color: #ececec; font-size: 15px;\"> <strong>{ _id: ObjectId(\"6203df361e95a9885e1e764a\"),\n  team: 'Mavs',\n  points: 30,\n  rebounds: 8 }\n{ _id: ObjectId(\"6203df361e95a9885e1e764b\"),\n  team: 'Spurs',\n  points: 35,\n  rebounds: 12 }\n{ _id: ObjectId(\"6203df361e95a9885e1e764c\"),\n  team: 'Rockets',\n  points: 20,\n  rebounds: 7 }\n{ _id: ObjectId(\"6203df361e95a9885e1e764d\"),\n  team: 'Warriors',\n  points: 25,\n  rebounds: 5 }\n{ _id: ObjectId(\"6203df361e95a9885e1e764e\"),\n  team: 'Cavs',\n  points: 23,\n  rebounds: 9 }\n{ _id: ObjectId(\"6203e17de42bfba74fc73325\"),\n  team: 'Hornets',\n  dots: '58',\n  rebounds: '20' }<\/strong><\/pre>\n<p> <span style=\"color: #000000;\">Observe que um novo documento foi adicionado para a equipe \u201cHornets\u201d.<\/span><\/p>\n<p> <span style=\"color: #000000;\"><strong>Nota<\/strong> : Voc\u00ea pode encontrar a documenta\u00e7\u00e3o completa da fun\u00e7\u00e3o <strong>$upsert<\/strong> <a href=\"https:\/\/docs.mongodb.com\/manual\/reference\/method\/Bulk.find.upsert\/\" target=\"_blank\" rel=\"noopener\">aqui<\/a> .<\/span><\/p>\n<h3> <span style=\"color: #000000;\"><strong>Recursos adicionais<\/strong><\/span><\/h3>\n<p> <span style=\"color: #000000;\">Os tutoriais a seguir explicam como realizar outras opera\u00e7\u00f5es comuns no MongoDB:<\/span><\/p>\n<p> <a href=\"https:\/\/statorials.org\/pt\/mongodb-adicionar-campo\/\" target=\"_blank\" rel=\"noopener\">MongoDB: Como adicionar um novo campo<\/a><br \/> <a href=\"https:\/\/statorials.org\/pt\/campo-de-exclusao-do-mongodb\/\" target=\"_blank\" rel=\"noopener\">MongoDB: Como excluir um campo<\/a><br \/> <a href=\"https:\/\/statorials.org\/pt\/conta-separada-mongodb\/\" target=\"_blank\" rel=\"noopener\">MongoDB: Como contar valores distintos em um campo<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Voc\u00ea pode usar a seguinte sintaxe para inserir um documento em uma cole\u00e7\u00e3o no MongoDB somente se ele ainda n\u00e3o existir: db.teams.update( { team: &#8216;Hornets&#8217; }, { $setOnInsert : {team: &#8216;Hornets&#8217;, points: &#8217;58&#8217;, rebounds: &#8217;20&#8217;} }, {upsert: true } ) Este c\u00f3digo espec\u00edfico verifica se o campo \u201cteam\u201d possui o valor \u201cHornets\u201d. Se esse valor [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[],"class_list":["post-2762","post","type-post","status-publish","format-standard","hentry","category-guia"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>MongoDB: Como inserir se n\u00e3o existir - Statorials<\/title>\n<meta name=\"description\" content=\"Este tutorial explica como inserir um novo documento em uma cole\u00e7\u00e3o no MongoDB se ele ainda n\u00e3o existir, com um exemplo.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/\" \/>\n<meta property=\"og:locale\" content=\"pt_PT\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"MongoDB: Como inserir se n\u00e3o existir - Statorials\" \/>\n<meta property=\"og:description\" content=\"Este tutorial explica como inserir um novo documento em uma cole\u00e7\u00e3o no MongoDB se ele ainda n\u00e3o existir, com um exemplo.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/\" \/>\n<meta property=\"og:site_name\" content=\"Statorials\" \/>\n<meta property=\"article:published_time\" content=\"2023-07-20T19:48:56+00:00\" \/>\n<meta name=\"author\" content=\"Dr. benjamim anderson\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Escrito por\" \/>\n\t<meta name=\"twitter:data1\" content=\"Dr. benjamim anderson\" \/>\n\t<meta name=\"twitter:label2\" content=\"Tempo estimado de leitura\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutos\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/\",\"url\":\"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/\",\"name\":\"MongoDB: Como inserir se n\u00e3o existir - Statorials\",\"isPartOf\":{\"@id\":\"https:\/\/statorials.org\/pt\/#website\"},\"datePublished\":\"2023-07-20T19:48:56+00:00\",\"dateModified\":\"2023-07-20T19:48:56+00:00\",\"author\":{\"@id\":\"https:\/\/statorials.org\/pt\/#\/schema\/person\/e08f98e8db95e0aa9c310e1b27c9c666\"},\"description\":\"Este tutorial explica como inserir um novo documento em uma cole\u00e7\u00e3o no MongoDB se ele ainda n\u00e3o existir, com um exemplo.\",\"breadcrumb\":{\"@id\":\"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/#breadcrumb\"},\"inLanguage\":\"pt-PT\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Lar\",\"item\":\"https:\/\/statorials.org\/pt\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Mongodb: como inserir se n\u00e3o existir\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/statorials.org\/pt\/#website\",\"url\":\"https:\/\/statorials.org\/pt\/\",\"name\":\"Statorials\",\"description\":\"O seu guia para a literacia estat\u00edstica!\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/statorials.org\/pt\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"pt-PT\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/statorials.org\/pt\/#\/schema\/person\/e08f98e8db95e0aa9c310e1b27c9c666\",\"name\":\"Dr. benjamim anderson\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"pt-PT\",\"@id\":\"https:\/\/statorials.org\/pt\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/statorials.org\/pt\/wp-content\/uploads\/2023\/10\/Dr.-Benjamin-Anderson-96x96.jpg\",\"contentUrl\":\"https:\/\/statorials.org\/pt\/wp-content\/uploads\/2023\/10\/Dr.-Benjamin-Anderson-96x96.jpg\",\"caption\":\"Dr. benjamim anderson\"},\"description\":\"Ol\u00e1, sou Benjamin, um professor aposentado de estat\u00edstica que se tornou professor dedicado na Statorials. Com vasta experi\u00eancia e conhecimento na \u00e1rea de estat\u00edstica, estou empenhado em compartilhar meu conhecimento para capacitar os alunos por meio de Statorials. Saber mais\",\"sameAs\":[\"https:\/\/statorials.org\/pt\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"MongoDB: Como inserir se n\u00e3o existir - Statorials","description":"Este tutorial explica como inserir um novo documento em uma cole\u00e7\u00e3o no MongoDB se ele ainda n\u00e3o existir, com um exemplo.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/","og_locale":"pt_PT","og_type":"article","og_title":"MongoDB: Como inserir se n\u00e3o existir - Statorials","og_description":"Este tutorial explica como inserir um novo documento em uma cole\u00e7\u00e3o no MongoDB se ele ainda n\u00e3o existir, com um exemplo.","og_url":"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/","og_site_name":"Statorials","article_published_time":"2023-07-20T19:48:56+00:00","author":"Dr. benjamim anderson","twitter_card":"summary_large_image","twitter_misc":{"Escrito por":"Dr. benjamim anderson","Tempo estimado de leitura":"2 minutos"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/","url":"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/","name":"MongoDB: Como inserir se n\u00e3o existir - Statorials","isPartOf":{"@id":"https:\/\/statorials.org\/pt\/#website"},"datePublished":"2023-07-20T19:48:56+00:00","dateModified":"2023-07-20T19:48:56+00:00","author":{"@id":"https:\/\/statorials.org\/pt\/#\/schema\/person\/e08f98e8db95e0aa9c310e1b27c9c666"},"description":"Este tutorial explica como inserir um novo documento em uma cole\u00e7\u00e3o no MongoDB se ele ainda n\u00e3o existir, com um exemplo.","breadcrumb":{"@id":"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/#breadcrumb"},"inLanguage":"pt-PT","potentialAction":[{"@type":"ReadAction","target":["https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/statorials.org\/pt\/mongodb-inserir-se-nao-existir\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Lar","item":"https:\/\/statorials.org\/pt\/"},{"@type":"ListItem","position":2,"name":"Mongodb: como inserir se n\u00e3o existir"}]},{"@type":"WebSite","@id":"https:\/\/statorials.org\/pt\/#website","url":"https:\/\/statorials.org\/pt\/","name":"Statorials","description":"O seu guia para a literacia estat\u00edstica!","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/statorials.org\/pt\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"pt-PT"},{"@type":"Person","@id":"https:\/\/statorials.org\/pt\/#\/schema\/person\/e08f98e8db95e0aa9c310e1b27c9c666","name":"Dr. benjamim anderson","image":{"@type":"ImageObject","inLanguage":"pt-PT","@id":"https:\/\/statorials.org\/pt\/#\/schema\/person\/image\/","url":"https:\/\/statorials.org\/pt\/wp-content\/uploads\/2023\/10\/Dr.-Benjamin-Anderson-96x96.jpg","contentUrl":"https:\/\/statorials.org\/pt\/wp-content\/uploads\/2023\/10\/Dr.-Benjamin-Anderson-96x96.jpg","caption":"Dr. benjamim anderson"},"description":"Ol\u00e1, sou Benjamin, um professor aposentado de estat\u00edstica que se tornou professor dedicado na Statorials. Com vasta experi\u00eancia e conhecimento na \u00e1rea de estat\u00edstica, estou empenhado em compartilhar meu conhecimento para capacitar os alunos por meio de Statorials. Saber mais","sameAs":["https:\/\/statorials.org\/pt"]}]}},"yoast_meta":{"yoast_wpseo_title":"","yoast_wpseo_metadesc":"","yoast_wpseo_canonical":""},"_links":{"self":[{"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/posts\/2762","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/comments?post=2762"}],"version-history":[{"count":0,"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/posts\/2762\/revisions"}],"wp:attachment":[{"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/media?parent=2762"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/categories?post=2762"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/statorials.org\/pt\/wp-json\/wp\/v2\/tags?post=2762"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}