How to arrive at the difference in values for minimum and maximum dates for each year in mongodb - mongodb-query

How to arrive at the difference in values of a specific column for the records with minimum and maximum dates for each year in a collection using the aggregate pipeline or map reduce in mongodb?
I have the following collection:
/* 1 */
{
"_id" : 1,
"item" : "abc",
"price" : 10,
"quantity" : 2,
"date" : ISODate("2014-01-01T08:00:00.000Z")
},
/* 2 */
{
"_id" : 2,
"item" : "jkl",
"price" : 20,
"quantity" : 1,
"date" : ISODate("2014-02-03T09:00:00.000Z")
},
/* 3 */
{
"_id" : 3,
"item" : "xyz",
"price" : 5,
"quantity" : 5,
"date" : ISODate("2014-02-03T09:05:00.000Z")
},
/* 4 */
{
"_id" : 4,
"item" : "abc",
"price" : 10,
"quantity" : 10,
"date" : ISODate("2014-02-15T08:00:00.000Z")
},
/* 5 */
{
"_id" : 5,
"item" : "xyz",
"price" : 5,
"quantity" : 10,
"date" : ISODate("2014-02-15T09:05:00.000Z")
},
/* 6 */
{
"_id" : 6,
"item" : "abc",
"price" : 10,
"quantity" : 2,
"date" : ISODate("2013-01-01T08:00:00.000Z")
},
/* 7 */
{
"_id" : 7,
"item" : "jkl",
"price" : 20,
"quantity" : 1,
"date" : ISODate("2013-02-03T09:00:00.000Z")
},
/* 8 */
{
"_id" : 8,
"item" : "xyz",
"price" : 5,
"quantity" : 5,
"date" : ISODate("2013-02-03T09:05:00.000Z")
},
/* 9 */
{
"_id" : 9,
"item" : "abc",
"price" : 10,
"quantity" : 10,
"date" : ISODate("2013-02-15T08:00:00.000Z")
},
/* 10 */
{
"_id" : 10,
"item" : "xyz",
"price" : 5,
"quantity" : 10,
"date" : ISODate("2013-02-15T09:05:00.000Z")
},
/* 11 */
{
"_id" : 11,
"item" : "abc",
"price" : 10,
"quantity" : 2,
"date" : ISODate("2012-01-01T08:00:00.000Z")
},
/* 12 */
{
"_id" : 12,
"item" : "jkl",
"price" : 20,
"quantity" : 1,
"date" : ISODate("2012-02-03T09:00:00.000Z")
},
/* 13 */
{
"_id" : 13,
"item" : "xyz",
"price" : 5,
"quantity" : 5,
"date" : ISODate("2012-02-03T09:05:00.000Z")
},
/* 14 */
{
"_id" : 14,
"item" : "abc",
"price" : 10,
"quantity" : 10,
"date" : ISODate("2012-02-15T08:00:00.000Z")
},
/* 15 */
{
"_id" : 15,
"item" : "xyz",
"price" : 5,
"quantity" : 10,
"date" : ISODate("2012-02-15T09:05:00.000Z")
},
I would like the result to take the following form:
{
{"year": 2014}, {"minDtQuantity": 2}, {"maxDtQuantity": 10}, {"quantityDiff": 8},
{"year": 2013}, {"minDtQuantity": 2}, {"maxDtQuantity": 10}, {"quantityDiff": 8},
{"year": 2012}, {"minDtQuantity": 2}, {"maxDtQuantity": 10}, {"quantityDiff": 8},
}
For each year, we need to find the minimum and maximum dates and group them by year and then find the "quantity" values on those dates and then find the difference between the quantities for the min and max dates for each year.
Is that even possible with aggregate pipelines or map-reduce in mongodb?

This can be done using aggregation pipelines by sorting by date, then pushing the quantities into arrays when grouping by the year (Use a the $year operator to extract the year from the date object). The quantities for the minimum and maximum dates in that year are then the first and last values in the array respectively. These can be taken out of the array using $arrayElemAt.
db.collection.aggregate(
[
{
$sort: {
"date": 1
}
},
{
$group: {
"_id": { "$year": "$date" },
"quantityArray": { "$push": "$quantity" },
}
},
{
$project: {
"_id": 0,
"year": "$_id",
"minDtQuantity": { "$arrayElemAt": [ "$quantityArray", 0 ] },
"maxDtQuantity": { "$arrayElemAt": [ { "$reverseArray": "$quantityArray" }, 0 ] },
"quantityDiff": { "$subtract": [
{ "$arrayElemAt": [ { "$reverseArray": "$quantityArray" }, 0 ] },
{ "$arrayElemAt": [ "$quantityArray", 0 ] },
] }
}
},
]
);
This aggregation returns these results on your data:
{
"year" : NumberInt(2014),
"minDtQuantity" : NumberInt(2),
"maxDtQuantity" : NumberInt(10),
"quantityDiff" : NumberInt(-8)
},
{
"year" : NumberInt(2013),
"minDtQuantity" : NumberInt(2),
"maxDtQuantity" : NumberInt(10),
"quantityDiff" : NumberInt(-8)
},
{
"year" : NumberInt(2012),
"minDtQuantity" : NumberInt(2),
"maxDtQuantity" : NumberInt(10),
"quantityDiff" : NumberInt(-8)
}
This is not quite the format you specified. I am not exactly sure what you required, did you need the results returned in one document?

Related

How could I create indexes in postgres using jsonb?

I have a table in my database as follows
my_table:jsonb
[ {
"name" : "world map",
"type" : "activated",
"map" : [ {
"displayOrder" : 0,
"value" : 123
}, {
"displayOrder" : 1,
"value" : 456
}, {
"displayOrder" : 2,
"value" : 789
} ]
}, {
"name" : "regional map",
"type" : "disabled"
} ]
I would like to create indices for the name, type and displayOrder fields, which would be the best way?

How to get last second of every minute from mongoDB using SQL query

I have a table with records for every millisecond. I need to get only the last second of every minute using Mongodb sql query.
Id Balance DataTime
1 "2462188.61" 2019-09-27T05:49:33.575+00:00
1 "2449426.30" 2019-10-30T19:30:52.513+00:00
1 "2456459.67" 2019-10-15T18:20:09.490+00:00
5 "1006266.91" 2019-10-31T13:48:18.290+00:00
I tried the LIKE condition but that didn't work.
Select Id, DateTime,Balance from AccountBalance where DateTime like '%59.000%'
Here is the link for the mongoldb SQL reference :
https://docs.mongodb.com/bi-connector/current/supported-operations/
I am using the BI connector to connect to Tableau(hence need the sql version of the query)
Thanks in advance!
You could try...
db.z.aggregate([
{ $addFields: {
year: { $dateToString: { format: "%Y", date: "$DataTime" } },
month: { $dateToString: { format: "%m", date: "$DataTime" } },
day: { $dateToString: { format: "%d", date: "$DataTime" } },
hour: { $dateToString: { format: "%H", date: "$DataTime" } },
minute: { $dateToString: { format: "%M", date: "$DataTime" } },
second: { $dateToString: { format: "%S", date: "$DataTime" } }
}
}
]).pretty()
This assumes your field DataTime is of type ISODate()...
Example Documents:
{ "_id" : ObjectId("5dea94c3b4ae6bbc17cd023b"), "Balance" : "2462188.61", "DataTime" : ISODate("2019-09-27T05:49:33.575Z") }
{ "_id" : ObjectId("5dea94c3b4ae6bbc17cd023c"), "Balance" : "2449426.30", "DataTime" : ISODate("2019-10-30T19:30:52.513Z") }
{ "_id" : ObjectId("5dea94c3b4ae6bbc17cd023d"), "Balance" : "2456459.67", "DataTime" : ISODate("2019-10-15T18:20:09.490Z") }
{ "_id" : ObjectId("5dea94c3b4ae6bbc17cd023e"), "Balance" : "1006266.91", "DataTime" : ISODate("2019-10-31T13:48:18.290Z") }
Example Query Output:
{
"_id" : ObjectId("5dea94c3b4ae6bbc17cd023b"),
"Balance" : "2462188.61",
"DataTime" : ISODate("2019-09-27T05:49:33.575Z"),
"year" : "2019",
"month" : "09",
"day" : "27",
"hour" : "05",
"minute" : "49",
"second" : "33"
}
{
"_id" : ObjectId("5dea94c3b4ae6bbc17cd023c"),
"Balance" : "2449426.30",
"DataTime" : ISODate("2019-10-30T19:30:52.513Z"),
"year" : "2019",
"month" : "10",
"day" : "30",
"hour" : "19",
"minute" : "30",
"second" : "52"
}
{
"_id" : ObjectId("5dea94c3b4ae6bbc17cd023d"),
"Balance" : "2456459.67",
"DataTime" : ISODate("2019-10-15T18:20:09.490Z"),
"year" : "2019",
"month" : "10",
"day" : "15",
"hour" : "18",
"minute" : "20",
"second" : "09"
}
{
"_id" : ObjectId("5dea94c3b4ae6bbc17cd023e"),
"Balance" : "1006266.91",
"DataTime" : ISODate("2019-10-31T13:48:18.290Z"),
"year" : "2019",
"month" : "10",
"day" : "31",
"hour" : "13",
"minute" : "48",
"second" : "18"
}
use sort function with date
eg:
db.collection.find().sort("Date_Field")

i want to query the double nested dates in mongodb

----------Query i have tried----------
db.getCollection('rates').aggregate([
{ $match: { "userId" : "5d4c4f69341b7b1746c80d13"}},
{ $unwind: '$ratewithdate.daywiserates'},{$match : {"$and" :
[{"ratewithdate.daywiserates.date" :{$gte :new ISODate("2019-09-
23T00:00:00.000Z")} },
{"ratewithdate.daywiserates.date" :{$lte :new ISODate("2019-09-
27T00:00:00.000Z")}}]}}])
-------------------------------------------------------------
In My query is here i want to know the query between two dates ,i want
get the data between two dates in the array? am unable to do that ,can
any one send me query,
here my question is i want get the date range from given date to next 30
days,i have tried with aggregate but data become slow..can any one suggest
any better solution for the making query formation
i have tried with aggregation as well find queries am not able find any
results,my goal here is find get the data between two dates,for example
if i selected 2019-09-23T10:43:14.239Z thi date from this date i wanna i
want to show the data.
please send me your value able suggestions to, am not bale to query with
double nested array queries in mongodb,please send me your value able
suggestions to,am not bale to query with double nested array queries in
mongodb please send me your value able suggestions to,
am not bale to query with double nested array queries in mongodb.
please send me your value able suggestions to, am not bale to query with
double nested array queries in mongodb,please send me your value able
suggestions to,am not bale to query with double nested array queries in
mongodb please send me your value able suggestions to,
am not bale to query with double nested array queries in mongodb
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1bff"),
"alloted_roomid" : [],
"name" : "working_rate3",
"description" : "bitcpin",
"type" : "room",
"value" : null,
"inclusive" : "General",
"refundable" : {
"cancellationWindow" : "",
"outsideWindowPenalty" : "",
"insideWindowPenalty" : ""
},
"nonRefundable" : true,
"cancellationWindow" : "",
"daysWiseRate" : "30",
"insideWindowPenalty" : "",
"outsideWindowPenalty" : "",
"deviations" : 980,
"policy" : "",
"funds" : "nonRefundable",
"vat" : 890,
"other_tax" : 90,
"roomRates" : [
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c00"),
"roomId" : ObjectId("5d7c8f2950a6c766c64b2a46"),
"roomName" : "Basic",
"rate" : 9888
}
],
"userId" : "5d4c4f69341b7b1746c80d13",
"hotelCode" : 10034,
"ratewithdate" : [
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c01"),
"roomCategory" : "Basic",
"roomId" : ObjectId("5d7c8f2950a6c766c64b2a46"),
"createdAt" : ISODate("2019-09-21T10:43:14.243Z"),
"daywiserates" : [
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c1f"),
"date" : ISODate("2019-09-21T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c1e"),
"date" : ISODate("2019-09-22T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c1d"),
"date" : ISODate("2019-09-23T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c1c"),
"date" : ISODate("2019-09-24T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c1b"),
"date" : ISODate("2019-09-25T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c1a"),
"date" : ISODate("2019-09-26T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c19"),
"date" : ISODate("2019-09-27T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c18"),
"date" : ISODate("2019-09-28T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c17"),
"date" : ISODate("2019-09-29T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c16"),
"date" : ISODate("2019-09-30T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c15"),
"date" : ISODate("2019-10-01T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c14"),
"date" : ISODate("2019-10-02T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c13"),
"date" : ISODate("2019-10-03T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c12"),
"date" : ISODate("2019-10-04T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c11"),
"date" : ISODate("2019-10-05T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c10"),
"date" : ISODate("2019-10-06T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c0f"),
"date" : ISODate("2019-10-07T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c0e"),
"date" : ISODate("2019-10-08T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c0d"),
"date" : ISODate("2019-10-09T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c0c"),
"date" : ISODate("2019-10-10T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c0b"),
"date" : ISODate("2019-10-11T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c0a"),
"date" : ISODate("2019-10-12T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c09"),
"date" : ISODate("2019-10-13T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c08"),
"date" : ISODate("2019-10-14T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c07"),
"date" : ISODate("2019-10-15T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c06"),
"date" : ISODate("2019-10-16T10:43:14.239Z"),
"rate" : 9888
},
{
"_id" : ObjectId("5d85fec2e8652a5c20ae1c05"),
"date" : ISODate("2019-10-17T10:43:14.239Z"),
"rate" : 9888
},
]
}
],
"id" : "rat-W262IxTjk",
"__v" : 0
}
Try this:
db.getCollection('rates').aggregate([
{ $match: { "userId" : "5d4c4f69341b7b1746c80d13"}},
{ $unwind: '$ratewithdate'},
{ $unwind: '$ratewithdate.daywiserates'},
{ $match : {
"$and" :[
{ "ratewithdate.daywiserates.date" :{$gte :new ISODate("2019-09-23T00:00:00.000Z")} },
{ "ratewithdate.daywiserates.date" :{$lte :new ISODate("2019-09-27T00:00:00.000Z")} }
]
}
},
{ $addFields: {result: "$ratewithdate.daywiserates"}},
{ $project: {result: 1, _id: 0}}
])

query collection A with filtered items from collection B

given the following 2 collections songs and play_log
i need a one mongo aggregation query with lookup to do the magic
to get the play log of all songs belonging to Bowie's "Scary Monsters" album with the song related info.
collection songs
[
{artist: 'David Bowie', title: 'Ashes to Ashes', album: 'Scary Monsters', year:'1980', track_number: 4 ,label: 'RCA Records'},
{artist: 'David Bowie', title: 'Fashion', album: 'Scary Monsters', year:'1980', track_number: 5 ,label: 'RCA Records'},
....
{artist: 'U2', title: 'Sunday Bloody Sunday', album: 'war', year '1983', track_number: 1, label: 'Island Records'},
{artist: 'U2', title: 'New Year's Day', album: 'war', year '1983', track_number: 3, label: 'Island Records'},
{artist: 'U2', title: 'The Refugee', album: 'war', year '1983', track_number: 6, label: 'Island Records'},
....
]
collection play_log
[
{ created: '2019-02-08T11:05:33', station: 'BBC Radio 6', artist: 'David Bowie', title: 'Ashes to Ashes' },
{ created: '2019-01-17T01:33:57', station: 'BBC Radio 1', artist: 'U2', title: 'Sunday Bloody Sunday' },
{ created: '2018-09-08T12:21:32', station: 'BBC Radio 2', artist: 'Morrissey', title: 'Every day is like Sunday' },
{ created: '2019-02-08T11:11:11', station: 'BBC Radio 4', artist: 'David Bowie', title: 'Fashion' },
...
]
expected result
[
{ created: '2019-02-08T11:05:33', station: 'BBC Radio 6', artist: 'David Bowie', title: 'Ashes to Ashes', album:'Scary Monsters', year:'1980', track_number: 4 ,label: 'RCA Records'},
{ created: '2019-02-08T11:11:11', station: 'BBC Radio 4', artist: 'David Bowie', title: 'Fashion', album: 'Scary Monsters', year:'1980', track_number: 5 ,label: 'RCA Records'},
...
]
This can be done through aggregation using $lookup operator as below:
db.play_log.aggregate([
// Join using artist fields
{
$lookup:
{
from: "songs",
localField: "artist",
foreignField: "artist",
as: "play_songs_logs"
}
},
// Filter any empty array found in newly created collection: play_songs_logs
{
$match: { "play_songs_logs": { $ne: [] } }
},
// Match only required album, this can be done before filter also if make aggregate on songs collection
{
$match:
{
"play_songs_logs.album" : "Scary Monsters"
}
},
// Push all elements or merged the elements
{
$replaceRoot: { newRoot: { $mergeObjects: [ { $arrayElemAt: [ "$play_songs_logs", 0 ] }, "$$ROOT" ] } }
},
// Filter not required fields
{ $project: { play_songs_logs: 0, _id:0 } }
])
Output of the above query:
{ "artist" : "David Bowie", "title" : "Ashes to Ashes", "album" : "Scary Monsters", "year" : "1980", "track_number" : 4, "label" : "RCA Records", "created" : "2019-02-08T11:05:33", "station" : "BBC Radio 6" }
{ "artist" : "David Bowie", "title" : "Fashion", "album" : "Scary Monsters", "year" : "1980", "track_number" : 4, "label" : "RCA Records", "created" : "2019-02-08T11:11:11", "station" : "BBC Radio 4" }
Before running above query, I have inserted the provided data and find query
> db.play_log.find()
{ "_id" : ObjectId("5c5f8c561765cd7b27eb4731"), "created" : "2019-02-08T11:05:33", "station" : "BBC Radio 6", "artist" : "David Bowie", "title" : "Ashes to Ashes" }
{ "_id" : ObjectId("5c5f8c561765cd7b27eb4732"), "created" : "2019-01-17T01:33:57", "station" : "BBC Radio 1", "artist" : "U2", "title" : "Sunday Bloody Sunday" }
{ "_id" : ObjectId("5c5f8c561765cd7b27eb4733"), "created" : "2018-09-08T12:21:32", "station" : "BBC Radio 2", "artist" : "Morrissey", "title" : "Every day is like Sunday" }
{ "_id" : ObjectId("5c5f8c561765cd7b27eb4734"), "created" : "2019-02-08T11:11:11", "station" : "BBC Radio 4", "artist" : "David Bowie", "title" : "Fashion" }
>
> db.songs.find()
{ "_id" : ObjectId("5c5f8c961765cd7b27eb4735"), "artist" : "David Bowie", "title" : "Ashes to Ashes", "album" : "Scary Monsters", "year" : "1980", "track_number" : 4, "label" : "RCA Records" }
{ "_id" : ObjectId("5c5f8c961765cd7b27eb4736"), "artist" : "David Bowie", "title" : "Fashion", "album" : "Scary Monsters", "year" : "1980", "track_number" : 5, "label" : "RCA Records" }
{ "_id" : ObjectId("5c5f8c961765cd7b27eb4737"), "artist" : "U2", "title" : "Sunday Bloody Sunday", "album" : "war", "year" : "1983", "track_number" : 1, "label" : "Island Records" }
{ "_id" : ObjectId("5c5f8c961765cd7b27eb4738"), "artist" : "U2", "title" : "New Year's Day", "album" : "war", "year" : "1983", "track_number" : 3, "label" : "Island Records" }
{ "_id" : ObjectId("5c5f8c961765cd7b27eb4739"), "artist" : "U2", "title" : "The Refugee", "album" : "war", "year" : "1983", "track_number" : 6, "label" : "Island Records" }
>
For details you can refer the official documents here: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

Why are items apparently duplicated in my mongoDB database when I use find()?

I am going through the try.mongodb.org tutorial on their website (embedded terminal emulator on the webpage). I am on items t4 and t5 (you type tx for items in the tutorial).
In t4 we populate a database.
> t4. Saving and Querying
> Try adding some documents to the scores collection:
> for(i=0; i<10; i++) { db.scores.save({a: i, exam: 5}) };
>
> Try that, then enter
> db.scores.find();
> to see if the save succeeded. Since the shell only displays 10 results at time,
> you'll need to enter the 'it' command to iterate over the rest.
>
> (enter 'next' when you're ready)
I made exam 5 + i just for fun:
for(i=0; i<10; i++) { db.scores.save({a: i, exam: 5+i}) };
So what is in the database? I type in db.scores.find(); and get the following, which is what I had expected, although the order seems random. Fine.
>
[
{ "exam" : 14, "a" : 9, "_id" : { "$oid" : "52b1d16bcc937439340649c4" } },
{ "exam" : 5, "a" : 0, "_id" : { "$oid" : "52b1d191cc937439340649c5" } },
{ "exam" : 6, "a" : 1, "_id" : { "$oid" : "52b1d191cc937439340649c6" } },
{ "exam" : 7, "a" : 2, "_id" : { "$oid" : "52b1d191cc937439340649c7" } },
{ "exam" : 8, "a" : 3, "_id" : { "$oid" : "52b1d191cc937439340649c8" } },
{ "exam" : 10, "a" : 5, "_id" : { "$oid" : "52b1d191cc937439340649c9" } },
{ "exam" : 9, "a" : 4, "_id" : { "$oid" : "52b1d191cc937439340649ca" } },
{ "exam" : 11, "a" : 6, "_id" : { "$oid" : "52b1d191cc937439340649cb" } },
{ "exam" : 12, "a" : 7, "_id" : { "$oid" : "52b1d191cc937439340649cc" } },
{ "exam" : 13, "a" : 8, "_id" : { "$oid" : "52b1d191cc937439340649cd" } }
]
In t5 we search for items in that database:
>
5. Basic Queries You've already tried a few queries, but let's make them more specific. How about finding all documents where a == 2:
db.scores.find({a: 2});
Or what about documents where a > 15? db.scores.find({a: {'$gt': 15}});
The a== 2 search worked, but the > 15 one did not. First of all, based on item t4, there should be no entry for a greater than 15.
So I try greater than 6: db.scores.find({a: {'$gt': 6}});
And I get the following output, which is really surprising to me since there should only be 3 entries for a == 7, a == 8, and a == 9.
>
[
{ "exam" : 14, "a" : 9, "_id" : { "$oid" : "52b1d16bcc937439340649c4" } },
{ "exam" : 12, "a" : 7, "_id" : { "$oid" : "52b1d191cc937439340649cc" } },
{ "exam" : 13, "a" : 8, "_id" : { "$oid" : "52b1d191cc937439340649cd" } },
{ "exam" : 14, "a" : 9, "_id" : { "$oid" : "52b1d191cc937439340649ce" } },
{ "exam" : 12, "a" : 7, "_id" : { "$oid" : "52b1d1a8cc937439340649d6" } },
{ "exam" : 13, "a" : 8, "_id" : { "$oid" : "52b1d1a8cc937439340649d7" } },
{ "exam" : 14, "a" : 9, "_id" : { "$oid" : "52b1d1a8cc937439340649d8" } },
{ "exam" : 5, "a" : 7, "_id" : { "$oid" : "52b1d49fcc937439340649f1" } },
{ "exam" : 5, "a" : 9, "_id" : { "$oid" : "52b1d49fcc937439340649f3" } },
{ "exam" : 5, "a" : 8, "_id" : { "$oid" : "52b1d49fcc937439340649f4" } }
]
If you look at the initially outputted db.scores.find() id's on the right, the last character goes up with each entry -- 4, 5, 6, 7, 8, 9, a, b, c, d. But in the duplicated entries, take a look at the entries for a == 9. We have one ending in 4, one ending in e, and one ending in 3. It seems like in the brains of the operation the database has 30 entries, not 10.
{ "exam" : 14, "a" : 9, "_id" : { "$oid" : "52b1d16bcc937439340649c4" } },
{ "exam" : 14, "a" : 9, "_id" : { "$oid" : "52b1d191cc937439340649ce" } },
{ "exam" : 5, "a" : 9, "_id" : { "$oid" : "52b1d49fcc937439340649f3" } },
I noticed is that if I try to repopulate the database using the loop in t4 it doesn't seem to re-write the values. i.e. if I use for(i=0; i<10; i++) { db.scores.save({a: i, exam: 5}) }; as the example had suggested instead of my just for fun for(i=0; i<10; i++) { db.scores.save({a: i, exam: 5+i}) };. Not sure if that is helpful to diagnose the problem but it is another observation.
You're missing something very special,
I noticed is that if I try to repopulate the database using the loop
in t4 it doesn't seem to re-write the values. i.e. if I use for(i=0;
i<10; i++) { db.scores.save({a: i, exam: 5}) }; as the example had
suggested instead of my just for fun for(i=0; i<10; i++) {
db.scores.save({a: i, exam: 5+i}) };. Not sure if that is helpful to
diagnose the problem but it is another observation.
Repopulate the database running the query more than once will create 10 rows every single time. db.scores.save doesn't know what document to update because you didn't refer to an _id field, in that case it will always create 10 records. To update existing records you should provide an _id field from the previous inserts. I'm sure you run it more than once and you expect to have always 10 records, what's happening is you're inserting 10 records every time.
Try it removing the collection, run the loop once and execute your find, it will work.
Are you sure you didn't run the commands more than once? What do you see if you run db.scores.find().count(), that will tell you how many items are in the table.