com.mongodb.hadoop.util.MongoPathRetriever Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mongo-hadoop-core Show documentation
Show all versions of mongo-hadoop-core Show documentation
The MongoDB Connector for Hadoop is a plugin for Hadoop that provides the ability to use MongoDB as an input source and/or an output destination.
package com.mongodb.hadoop.util;
import org.bson.BSONObject;
import java.util.List;
/**
* Utility class providing a mechanism for retrieving data nested within
* a MongoDB document.
*/
public final class MongoPathRetriever {
private MongoPathRetriever() {}
/**
* Returns the Object stored at a given path within a MongoDB
* document. Returns null
if the path is not found.
*
* @param document MongoDB document in which to search.
* @param path Dot-separated path to look up.
* @return the Object stored at the path within the document.
*/
public static Object get(final BSONObject document, final String path) {
String[] parts = path.split("\\.");
Object o = document;
for (String part : parts) {
if (null == o) {
return null;
} else if (o instanceof List) {
try {
int index = Integer.parseInt(part);
if (((List) o).size() > index && index >= 0) {
o = ((List) o).get(index);
} else {
return null;
}
} catch (NumberFormatException e) {
return null;
}
} else if (o instanceof BSONObject) {
o = ((BSONObject) o).get(part);
} else {
// Hit a leaf before finding the key we were looking for.
return null;
}
}
return o;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy