MONGO仅获得文档名称,而不是整个文档

编程入门 行业动态 更新时间:2024-10-27 04:25:28
本文介绍了MONGO仅获得文档名称,而不是整个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

查询mongo仅查找名称:以一种快速的方式进行,即我不想获取每个文档,然后从每个文档中获取名称.

query mongo to find only the names : in such a way that it should be fast, ie i don't want to get each document and then get the name from each of them.

我是mongo的新手,dbpany.find()->这将给出整个文件,非常大

I am new to mongo, dbpany.find() --> this will give whole document Which is VERY BIG

注意;我已将索引用于公司名称&也是独特的条件.o->我认为这应该可以帮助我快速找到公司名称,很容易但是我不知道

NOTE ; i have used indexing to the company name & also the unique condition too. soo --> i think it should help me finding the company name fast and easily , BUT i don't know how

这是收藏集

collection company : --> list of companies in the collection { { "_id": "5b8ed214b460e7c17c5a33f9", "company_location": "USA", "company_name": "tesla", -----> COMPANY NAME: TESLA "cars": [ {---car 1---} , {---car 2---} , {---car n---} ], }, { "_id": "5b8ed214b460e7c17c5a33f9", "company_location": "USA", "company_name": "gmc", -----> COMPANY NAME :GMC "cars": [ {---car 1---} , {---car 2---} , {---car n---} ], }, { "_id": "5b8ed214b460e7c17c5a33f9", "company_location": "USA", "company_name": "bmw", -----> COMPANY NAME:BMW "cars": [ {---car 1---} , {---car 2---} , {---car n---} ], }, { "_id": "5b8ed214b460e7c17c5a33f9", "company_location": "USA", "company_name": "audi", -----> COMPANY NAME: AUDI "cars": [ {---car 1---} , {---car 2---} , {---car n---} ], }, }

所以,我只想要公司名称列表,而不是使用 dbpanies.find()的整个公司集合.->然后遍历查找它们的名称

So I just want the list of company names, and not the whole company collection using dbpanies.find(). --> and then finding the names of each of them by traversing it

我该怎么做:必须快速,数据量巨大

推荐答案

您可以使用 .find()方法的第二个参数指定投影:

You can use second parameter of .find() method to specify a projection:

dbpanies.find({}, { _id: 0, company_name: 1 })

返回:

{ "company_name" : "gmc" } { "company_name" : "tesla" } ...

或者您可以使用Aggregation Framework来获取带有名称数组的单个文档:

Or you can use Aggregation Framework to get single document with an array of names:

dbpanies.aggregate([{ $group: { _id: null, company_names: { $push: "$company_name" } } }])

返回:

{ "_id" : null, "company_names" : [ "gmc", "tesla", ... ] }

如果在 company_name 上有索引,第一个应该是最快的方法.在这种情况下,您的查询不需要扫描集合,而只能使用索引来获取查询的数据(已覆盖查询).

First one should be the fastest way if you have an index on company_name. In that case your query don't need to scan collection and can use only index to get queried data (covered query).

更多推荐

MONGO仅获得文档名称,而不是整个文档

本文发布于:2023-10-23 22:27:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1522179.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   而不是   名称   MONGO

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!