I have got records in my collection as shown below
{
"_id" : ObjectId("53722c39e4b04a53021cf3c6"),
"symbol" : "AIA",
"tbq" : 1356,
"tsq" : 0,
"tquan" : 6831336,
"tvol" : 17331.78,
"bquantity" : 1356,
"squantity" : 0
}
{
"_id" : ObjectId("53722c38e4b04a53021cf3c1"),
"symbol" : "SAA",
"tbq" : 0,
"tsq" : 9200,
"tquan" : 6036143,
"tvol" : 50207.43,
"bquantity" : 0,
"squantity" : 9200
}
I am displaying the results in the ascending order of bquantity, and also at the same time I want to display only certain columns in the result (symbol, bquantity, squantity) and ignore the rest.
I tried with the below query, but still its displaying all the fields .
Please tell me how can i eliminate those fields from the result ?
db.stock.find().sort(
{"bquantity":-1},
{
symbol: 1,
bquantity: 1,
squantity:1 ,
_id:0,
tbq:0,
tsq:0,
tquan:0,
tvol:0
}
)
The field filter is a parameter to the find function, not to the sort function, i.e.:
db.stock.find({}, { _id:0,tbq:0, tsq:0,tquan:0,tvol:0}).sort({"bquantity":-1})
The empty hash used as first parameter to find is required as an 'empty query' which matches all documents in stock.
Related
I’m trying to fetch some data from appointment table. But when execute the following code, data not fetching. In my mongo I have data with matching criteria. Any help would be appreciated advance.
Can anyone check the condition which I’m giving right or wrong.
var timePeriod = {
to: 1512412200000,
from: 1511807400000
}
var List= appointment.find({$and:[{‘appointmentDate’:
{$gte:Number(timePeriod.from)}},{‘appointmentDate’:
{lte:Number(timePeriod.to)}},
{‘url’:{$eq:‘boaseenterprises.ezvisitor.com’}}]}).fetch();
mongo collection data
{
"_id" : “SpwCxi4CsxDFanvrf”,
“appointmentDate” : 1511952239000.0,
“appointmentTime” : 1511952239000.0,
“appointmentEndDate” : 1511955839000.0,
“appointmentEndTime” : 1511955839000.0,
“purpose” : “t”,
“hostName” : “boase”,
“status” : “pending”,
“hostId” : “Tct2pRanpHW5pju6A”,
“url” : “boaseenterprises.ezvisitor.com”,
“visitorsList” : [
{
“id” : “9i8u9tFwyuFi7xjmE”,
“name” : “test1”,
“signIn” : 0,
“signOut” : 0
}
]
}
Looking at your query, you are trying to find all those appointments which is between timePeriod.from and timePeriod.to and where url is boaseenterprises.ezvisitor.com
appointment.find({
appointmentDate: {$gte:timeperiod.from},
appointmentDate: {$lt:timePeriod.to},
url : "boaseenterprises.ezvisitor.com"
}).fetch();
I'm newbie for manipulating MongoDB recently, but I really need to update some fields like these..
db_name: test
table_name: info
{
"_id" : ObjectId("54bf9ab4f8eda6747567b122"),
"archives" : [
{
"evalution" : {
"positive" : 0,
"undefine" : 0,
"negative" : 0
},
"source" : ObjectId("54cb6f455decd8037528756b")
}
]
}
I want to increase positive and undefine by 1, and if evalution doesn't exists,
"evalution" : {
"positive" : 0,
"undefine" : 0,
"negative" : 0
}
should be added to the object.
I don't know if I express myself clearly, but I really need some help..
If evalution doesn't exists u can create a sub-doc using following query.
db.test.update(
{_id:ObjectId("54bf9ab4f8eda6747567b122"),
"archives.source" : ObjectId("54cb6f455decd8037528756b"),
"archives.evalution":{$exists:false}},
{$set:{"archives.$.evalution":{positive:1,negative:0,undefine:1}}}
)
NOTE: Positional operator is only upto one level, so u cannot increment the values until you know the index of archieves array.
you get the the index of the archieves array and increment using following command. In this case 0 where
source = ObjectId("54cb6f455decd8037528756b")
db.test.update(
{_id:_id:ObjectId("54bf9ab4f8eda6747567b122")},
{$inc:{"archives.0.evalution.positive":1}}
)
It would help to know what the semantics of the update are. Why are you incrementing those two fields? Why are you incrementing two fields, as if doing a count, but if the fields don't exist you want to set default values to 0 (as opposed to, say, 1)? Is there a semantic difference between "evaluation doesn't exist" and the value
{
"positive" : 0,
"undefine" : 0,
"negative" : 0
}
for evaluation? Or between "evaluation doesn't exist" and
{
"positive" : -1,
"undefine" : -1,
"negative" : 0
}
for the value? It seems like no, for at least one of those default values, and so you should set evaluation to have the appropriate default value on insert of the document or of the array element. If you do that, your update is simple:
db.info.update(
{
"_id" : ObjectId("54bf9ab4f8eda6747567b122"),
"archives.source" : ObjectId("54cb6f455decd8037528756b")
},
{
"$inc" : {
"archives.$.evalution.positive" : 1,
"archives.$.evalution.undefine" : 1,
}
}
)
Also, you have some typos, I think:
evalution probably means evaluation or possibly evolution?
the proper complement to positive and negative is undefined
Today is my first day using MongoDB
My collection format:
{ "_id" : "ObjectId" :"4f2ff1d00cf2f86576f91a91"),
"fishStuff" : [
{
"name" : "GreatWhite",
"fID" : 50
},
{
"name" : "Hammerhead",
"fID" : 51
},
{
"name" : "White",
"fID" : 60
}
], "fishSpecies" : "Oceanic"
...
I want to write a query in the shell (straight up mongo) that will delete the third child (name: White) because the 1st child exists in this group of "fishStuff".
I believe the "where" clause should be :
{fishSpecies:"Oceanic","fishStuff.fID":50, "fishStuff.fID:60}
So how do I delete the entire "60" child element? I want to delete every "60" element in the collection when "50" is also in the same "fishStuff" group/array. Also, the reason I've included fishSpecies in the "where" clause is because there is more than one fishSpecies possibility.
UPDATE:
I have tried the suggestions left by the two commenters below and am still getting 7 instances (after running the count below) of child object sets that contain both fID 50 and 60:
> db.fish.update({fishSpecies:"oceanic","fishStuff.fID":50}, {$pull : {"fishStuff" : { fID : 60}}},false, true)
> db.fish.find({"fishSpecies":"oceanic","fishStuff.fID":50, "fishStuff.fID":60}).count()
7
The multi: true flag does not work (or I am not implementing it correctly) as zero records are updated.
I believe this is what you're looking for...
Checks mycollection for documents that match fishSpecies with Oceanic AND fID = 50- removes fID = 60 element if so. multi:true scans the entire collection.
db.mycollection.update({'fishSpecies': 'Oceanic','fishStuff':{fID:50}}, {$pull:{'fishStuff': {fID: 60}}}, {multi:true})
If you're trying to remove based on it's ordinal position (index) then you can't directly.
You can use a technique to $unset the item in the array then $pull it.
db.mycollection.update({}, {$unset : {"fishStuff.50" : 1 }})
db.mycollection.update({}, {$pull : {"fishStuff" : null}})
It's worth noting though, this doesn't take into account the fId, and solely relies on the document's position in the array.
To pull the item matching your fId you need to:
db.mycollection.update({}, {$pull : {"fishStuff" : { fId : 50}}})
EDIT:
If you're wanting to remove the elements where fId == 50 from the array where the document's array contains fId == 50 and fId == 60 you should be able to:
db.mycollection.update({
"fishSpecies":"oceanic",
"fishStuff.fId": { $all : [50,60]}},
// update
{$pull : {"fishStuff" : { fId : 50}}
})
I have a Mongo find query that works well to extract specific fields from a large document like...
db.profiles.find(
{ "profile.ModelID" : 'LZ241M4' },
{
_id : 0,
"profile.ModelID" : 1,
"profile.AVersion" : 2,
"profile.SVersion" : 3
}
);
...this produces the following output. Note how the SVersion comes before the AVersion in the document even though my projection asked for AVersion before SVersion.
{ "profile" : { "ModelID" : "LZ241M4", "SVersion" : "3.5", "AVersion" : "4.0.3" } }
{ "profile" : { "ModelID" : "LZ241M4", "SVersion" : "4.0", "AVersion" : "4.0.3" } }
...the problem is that I want the output to be...
{ "profile" : { "ModelID" : "LZ241M4", "AVersion" : "4.0.3", "SVersion" : "3.5" } }
{ "profile" : { "ModelID" : "LZ241M4", "AVersion" : "4.0.3", "SVersion" : "4.0" } }
What do I have to do get the Mongo JavaScript shell to present the results of my query in the field order that I specify?
I have achieved it by projecting the fields using aliases, instead of including and excluding by 0 and 1s.
Try this:
{
_id : 0,
"profile.ModelID" :"$profile.ModelID",
"profile.AVersion":"$profile.AVersion",
"profile.SVersion":"$profile.SVersion"
}
I get it now. You want to return results ordered by "fields" rather the value of a fields.
Simple answer is that you can't do this. Maybe its possible with the new aggregation framework. But this seems overkill just to order fields.
The second object in a find query is for including or excluding returned fields not for ordering them.
{
_id : 0, // 0 means exclude this field from results
"profile.ModelID" : 1, // 1 means include this field in the results
"profile.AVersion" :2, // 2 means nothing
"profile.SVersion" :3, // 3 means nothing
}
Last point, you shouldn't need to do this, who cares what order the fields come-back in.
You application should be able to make use of the fields it needs regardless of the order the fields are in.
Another solution I applied to achieve this is the following:
db.profiles
.find({ "profile.ModelID" : 'LZ241M4' })
.toArray()
.map(doc => ({
profile: {
ModelID: doc.profile.ModelID,
AVersion: doc.profile.AVersion,
SVersion: doc.profile.SVersion
}
}))
Since version 2.6 (that came out in 2014) MongoDB preserves the order of the document fields following the write operation (source).
P.S. If you are using Python you might find this interesting.
While trying to setup to use the Geospatial Index on MongoDB, I run into the error message that the location array is not in the correct format.
This is my collection "test".
{
"_id" : ObjectId("4f037ac176d6fdab5b00000a"),
"CorporateId" : "XYZ12345",
"Places" : [
{
"Location" : {
"Longitude" : "50.0",
"Latitude" : "50.0"
},
"ValidFrom" : "2011-11-01 00:00:00",
"ValidTo" : "2021-12-31 00:00:00",
"itemCount" : "1"
}
]
}
Once I run this code.
db.test.ensureIndex({"Places.Location": "2d"});
I get this error message
location object expected, location array not in correct format
My assumption is that the Long/Lat needs to be a number.
Currently it is an object.
typeof db.test.Places.Location.Longitude -> Object
typeof db.test.Places.Location -> Object
My problem is that since I am still quite new to MongoDB, I don't really know how to approach this problem in the best way.
Mongodb expects numbers for the coordinates while you passed in a string.
"Location" : {
"Longitude" : 50.0, // <<<<<<<<<<<<<< use numbers instead
"Latitude" : 50.0
},
see http://www.mongodb.org/display/DOCS/Geospatial+Indexing for details.
The problem has been fixed by converting the Location parameters into a float type like this.
$var = $JSonString['Places'];
$test=count($var);
$i=0;
for ( $i=0; $i<$test;$i++){
$lon = (float)$JSonString['Places'][$i]['Location']['Longitude'];
$lat = (float)$JSonString['Places'][$i]['Location']['Latitude'];
$JSonString['Places'][$i]['Location']['Longitude'] =$lon ;
$JSonString['Places'][$i]['Location']['Latitude'] =$lat ;
//error_log($lon . "->".gettype($JSonString['Places'][$i]['Location']['Latitude']), 3 , "/var/tmp/my-errors.log");
}