MongoDB - Querying a field in a lower level of document - mongodb

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

Related

Firestore arrayUnion on aggragated array of objects?

I want to arrayUnion the votes field from the following document:
{
answers: [
{
title: "title"
votes: [
"id1",
"id2",
]
}
]
}
It's important to me to use arrayUnion since I need to use an atomic operation (in case a user goes offline and then back online).
Since your answers field is an array value, you'll need to specify the entire value of the array item when using arrayUnion on that field. There is no way to use an arrayUnion operation on the nested votes subfield in there, as that'd be providing a partial update to an array item, which isn't a supported operation.
So you'll have to :
Read the document and get the entire answers field from it into your application code.
Modify the correct array item with the new votes subvalue.
Write the entire array back to the database.

MongoDB return only matched sub-sub document

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.

How can I query for a subdocument full of objects in Mongo?

So I have a document with an unknown number of objects in it, each with 2 properties. It's a collection of friend lists, and I'm trying to confirm if someone has a friend with a certain username before I allow a user to send a request. I'm keeping the list of friends in a subdocument, like this:
>>all the _id and other properties<<, "ownerFriends":[{"friendId":"an id goes here", "friendUsername": "username"}, {"friendId":"another id", "friendUsername":"username2"}]
I'm trying to do a query that will return username2 if given that as input, but I don't know how to do that with dot notation because I think you need to know the specific property to look for, and these are heterodox amounts of friend objects in the ownerFriends property.
If you want to select the ownerFriend object that has username as the friendUserName you can use the following selector (assuming your collection is called Friends):
Friends.find({
"ownerFriends.friendUsername": "username2"
}, {
fields: { "ownerFriends.$": 1}
});
You can find a detailed explanation of how to query an array of objects based on a property here:
http://www.curtismlarson.com/blog/2015/08/08/meteor-mongodb-array-property-selector/
In summary you have an object that contains keys, one of whose values is an array of objects. You can perform queries on the arrays using $elemMatch In your case:
MyCollection.find({ ownerFriends: { $elemMatch: { friendUsername: searchString }}});
Although I think you'll need to also query on the current user's _id. Not knowing the details of your collection, I can only speculate with:
MyCollection.find({ userId: Meteor.userId(), ownerFriends: { $elemMatch: { friendUsername: searchString }}});

Get text words from query

I've read the MongoDB documentation on getting the indexes within a collection, and have also searched SO and Google for my question. I want to get the actual indexed values.
Or maybe my understanding of how MongoDB indexes is incorrect. If I've been indexing a field called text that contains paragraphs, am I right in thinking that what gets indexed is each word in the paragraph?
Either case I want to retrieve the values that were indexed, which db.collection.getIndexes() doesn't seem to be returning.
Well yes and no, in summary.
Indexes work on the "values" of the fields they are supplied to index, and are much like a "card index" in that there is a point of reference to look at to find the location of something that matches that term.
What "you" seem to be asking about here is "text indexes". This is a special index format in MongoDB and other databases as well that looks at the "text" content of a field and breaks down every "word" in that content into a value in that "index".
Typically we do:
db.collection.createIndex({ "text": "text" })
Where the "field name" here is "text" as you asked, but more importantly the type of index here is "text".
This allows you to then insert data like this:
db.collection.insert({ "text": "The quick brown fox jumped over the lazy dog" })
And then search like this, using the $text operator:
db.collection.find({ "$text": { "$search": "brown fox" } })
Which will return and "rank" in order the terms you gave in your query depending how they matched the given "text" of your field in the index on your collection.
Note that a "text" index and it's query does not interact on a specific field. But the index itself can be made over multiple fields. The query and the constraints on the "index" itself are that there can "only be one" text index present on any given collection otherwise errors will occur.
As per mongodb's docs:
"db.collection.getIndexes() returns an array of documents that hold index information for the collection. Index information includes the keys and options used to create the index. For information on the keys and index options, see db.collection.createIndex()."
You first have to create the index on the collection, using the createIndex() method:
db.records.createIndex( { userid: 1 } )
Queries on the userid field are supported by the index:
Example:
db.records.find( { userid: 2 } )
db.records.find( { userid: { $gt: 10 } } )
Indexes help you avoid scanning the whole document. They basically are references or pointers to specific parts of your collection.
The docs explain it better:
http://docs.mongodb.org/manual/tutorial/create-an-index/

How to Retrieve any element value from mongoDB?

Suppose I have following collection :
{ _id" : ObjectId("4f1d8132595bb0e4830d15cc"),
"Data" : "[
{ "id1": "100002997235643", "from": {"name": "Joannah" ,"id": "100002997235643"} , "label" : "test" } ,
{ "id1": "100002997235644", "from": {"name": "Jon" ,"id": "100002997235644"} , "label" : "test1" }
]" ,
"stat" : "true"
}
How can I retrieve id1 , name , id ,label or any other element?
I am able to get _id field , DATA (complete array) but not the inner elements in DATA.
You cannot query for embedded structures. You always query for top level documents. If you want to query for individual elements from your array you will have to make those element top level documents (so, put them in their own collection) and maintain an array of _ids in this document.
That said, unless the array becomes very large it's almost always more efficient to simply grab your entire document and find the appropriate element in your app.
I don't think you can do that. It is explained here.
If you want to access specific fields, then following MongoDB Documentation,
you could add a flag parameter to your query, but you should redesign your documents for this to be useful:
Field Selection
In addition to the query expression, MongoDB queries can take some additional arguments. For example, it's possible to request only certain fields be returned. If we just wanted the social security numbers of users with the last name of 'Smith,' then from the shell we could issue this query:
// retrieve ssn field for documents where last_name == 'Smith':
db.users.find({last_name: 'Smith'}, {'ssn': 1});
// retrieve all fields *except* the thumbnail field, for all documents:
db.users.find({}, {thumbnail:0});