本文介绍了在MongoDB中获取文档而不指定集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
MongoDB ID对于单个数据库集群是唯一的。是否可以使用ID来获取文档,而不指定集合名称?
MongoDB IDs are unique for a single database cluster. Is it possible to get documents using their IDs, without specifying the collection name?
如果是,如何?
如果没有,为什么不?
推荐答案
是,但不是以可扩展的方式(因为您必须查询每个集合)。如果你有2或3个集合,这可能是确定,但...你可能应该审查你的设计,找出你为什么这样做。
Yes, but not in a scalable way (since you must query each collection). If you have 2 or 3 collections, this might be ok, but... you probably should review your design to figure out why you're doing this. Why are you, by the way?
- 您将获得数据库中所有集合的列表。
- 您循环浏览它们,并根据_id
查询
示例shell代码:
db.test1.save({});
db.test2.save({});
db.test3.save({});
db.test4.save({});
db.test5.save({});
db.test6.save({});
db.test2.findOne(); // gives: { "_id" : ObjectId("4f62635623809b75e6b8853c") }
db.getCollectionNames().forEach(function(collName) {
var doc = db.getCollection(collName).findOne({"_id" : ObjectId("4f62635623809b75e6b8853c")});
if(doc != null) print(doc._id + " was found in " + collName);
});
给出: 4f62635623809b75e6b8853c在test2中找到
这篇关于在MongoDB中获取文档而不指定集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!