In mongodb, i can find all those records in a collection in database db that contain a particular field using the following query
var doc = db.collection_name.find({field_name:{$exists:true}})
Now consider the following document:
{
"somefield":"someval",
"metadata": {"id":"someval",
"client_url":"http://www.something.com"
}
}
What would be the query for getting all records having the id field in metadata ?
Please Help.
Thank You
You can use dot notation to reference sub-document fields
var doc = db.collection_name.find({"metadata.id":{$exists:true}})
Related
I'm just switching from MySQL to MongoDB and it's a little confusing. We have our database stored in MongoDB and using Java-Selenium in the front end. I am trying to retrieve just one single data from the database. The code below retrieves all the data present in the database:
DBCursor cursor = dbCollection.find();
while(cursor.hasNext())
{
int i=1;
System.out.println(cursor.next());
i++;
}
This is my database lets say:
{
"name" : "Su_123",
"email" : "test#gmail.com",
"_id" : ObjectId("12345656565656")
}
I want to retrieve just the email field (test#gmail.com) from the document where _id = ObjectId("12345656565656") and store this in a String field.
How do I go about coding this? find() retrieves the entire row.
For newer drivers, since 3.7.1
To get specific document that matches a filter:
Document doc = collection.find(eq("email", "test#gmail.com")).first();
It can be used to find the first document where the field email has the value test#gmail.com. And pass an eq filter object to specify the equality condition.
By the same logic using id:
Document document = myCollection.find(eq("_id", new ObjectId("12345656565656"))).first();
To get specific value of the field from selected document:
String value = (String) doc.get("email");
For older drivers like 2.14.2 and 2.13.3
To get a single document with a query:
BasicDBObject query = new BasicDBObject("email", "test#gmail.com");
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
//System.out.println(cursor.next());
}
} finally {
cursor.close();
}
To see more details for newer Mongodb Java driver.
To see more details for older Mongodb Java driver.
To see more details from Mongodb Official Docs.
Issue with fetching the data of a particular field within a document
The followoing is my collection structure
colleciton mail
mailtype
criteria
triggerinfor
code ----> multiple codes are there.
description
status
Tried this but not working
db.getCollection('Mail').find(
{
"MailType" :"Printed",
"MailName" :"Welcomemail",
"programType":"Maile",
"criterias" :
{"triggerInformation":
{"code" :"MAIL007"},
{"description":"1234 Welcome maile"}
}
}
)
I have to retrieve the document with code MAIL007 only.. could some one help in getting a query for that
There are two ways to do it, depending on what you need:
1- Matching an exact nested document: this way, you are querying for documents that have a nested document that is exactly like the one in your search criteria.
db.getCollection('Mail').find(
{
"MailType" :"Printed",
"MailName" :"Welcomemail",
"programType":"Maile",
"criterias.triggerInformation": {
"code": "MAIL007",
"description": "1234 Welcome maile",
"status": "some status"
}
}
Notice that you need to explicitly inform a value to each of the nested document fields in your search criteria. If any field is missing the query will return nothing.
2- Querying a field inside a nested document: this way, you are querying for documents based on the value of one or more fields inside a nested document.
db.getCollection('Mail').find({
"MailType":"Printed",
"MailName":"Welcomemail",
"programType":"Maile",
$and: [
{"criterias.triggerInformation.code": "MAIL007"},
{"criterias.triggerInformation.description": "description":"1234 Welcome maile"}
]
})
In the code above you are querying for documents based on the values of the fields code and description inside the nested document criterias.triggerInformation.
You can find more info about querying nested documents at MongoDB's docs here
Given the above document structure, in mongodb, how do you guys filter a specific terminal whose id matches the given parameter?
Assuming your JSON looks like this, or similar:
{
"Merchant_Account":"Merchant Name",
"ID":"MA1",
"Card_Acceptor":[{
"ID":"CA1",
"Vendor_ID":{
"ID":"VID1"
},
"Terminal_ID":[
"TID1",
"TID2",
"TID3"
]
}]
}
You can retrieve this document using the following in Mongo Shell:
db.collection.find({"Card_Acceptor":{$elemMatch:{Terminal_ID:"TID1"}}})
This returns the whole document where a Terminal ID matches in the array of Terminal_IDs. The key here is the $elemMatch array query operator.
A mongo db has documents that look like:
{
"_id": : ObjectId("55cb43e8c78b04f43f2eb503"),
<some fields>
"topics": {
"test/23/result": 149823788,
"test/27/result": 147862733,
"input/misc/test": 14672882
}
}
I need to find all documents that have a topics field that contains a particular key. i.e. find all documents that have a topics.key = "test/27/result"
I've tried a number of things but none work yet, neither attempt below work,
they return no records event though some should match:
db.collName.find({"topics.test/27/result": {$exists:true}});
db.collName.find({"topics.test\/27\/result": {$exists:true}});
How can I make the query work?
The slash characters are inserted by another process. They are mqtt topic names.
I found the solution to my problem:
I was building the query wrong in my code. In the example below, evtData.source contains the key name to search for, i.e. 'test/27/result'
The query methodology that works for me is:
var query = {};
query['topics.' + evtData.source] = {$exists: true};
db.collName.find(query)
I have imported a csv file into a collection,
My document saved like
"_id" : "ObjectID(53874d952f92e2af1a5f0afb)"
I was unable to query this
Can anyone help me to remove quotations for ObjectId
Lets assume your collection name is myCollection.
Do this :
db.myCollection.forEach(function(doc) {
var oldId = doc._id;
var newIdStr = doc._id.replace(/ObjectID\((\w+)\)/g,"\$1");
var newObjId = ObjectId(newIdStr);
doc._id = newObjId;
db.myCollection.save(doc);
db.myCollection.remove({_id:oldId});
});
CSV does not fully preserve the types of your fields and can present strings and integers (not Object_ids). If I were you, I would write an a parser in the most suitable language and convert your _id in objectIds there.
Another approach (if your _ids are not important) you can change _id in csv header to any other name and during the import mongo will create new ids, then you will go and remove your created field.
Next time you can use mongodump and mongorestore to preserve the types.