mongodb update single object in array - mongodb

How to update Single object in array of objects by rules query is that object must by in document that has translation_key == as input that i read and object must have same language (id) if not i must create new object . ( mongodb, mongoose)
Language are required and uniueq in translations
{
"_id" : ObjectId("5bfd5324725fb12bc4863cd8"),
"deleted" : false,
"deleted_at" : null,
"noAuth" : false,
"hidden" : false,
"translation_key" : "Standard",
"translation_type" : "text",
"translation" : [
{
"system" : {
"android" : false,
"ios" : false,
"web" : false,
"api" : false
},
"language" : ObjectId("5bf52e06edb9902e2113d8b3"),
"text":'',
"active" : false,
"prepared_string" : false,
"_id" : ObjectId("5bfd910c2998d929644abd90"),
"params" : []
},
{
"system" : {
"android" : false,
"ios" : false,
"web" : true,
"api" : false
},
"active" : false,
"prepared_string" : false,
"_id" : ObjectId("5bfdb5d22998d929644ac2af"),
"language" : ObjectId("5bf52e06edb9902e6471d8c1"),
"text" : "Standard",
"app_version" : "2.0",
"params" : []
}
],
"create_date" : ISODate("2018-11-27T14:22:28.635Z"),
"update_date" : ISODate("2018-11-27T14:22:28.635Z"),
"__v" : 3
}

Model.findOneAndUpdate(
{
_id: "document_id",
"translation.language": "languageId",
},
{
$set: {
"translation.$.text: "text",
"translation.$.active": "status",
"translation.$.system.android" : true
},
{ new: true, upsert: true, }
)
.lean();

Related

How to find documents using a field of an embedded document that is inside an array?

I have the Data/Schema for my student records:
{
"_id" : ObjectId("579ed0ba7d509178a97fae8f"),
"fullName" : "ABC",
"enroll" : "AB1234",
"profile" : {
"isCompleted" : true,
"verification" : [
{
"pro" : true,
"verifiedBy" : "ProAct",
"verifiedOn" : ISODate("2016-09-12T07:36:53.680Z")
},
],
"isChecked" : false,
"fullName" : "ABC",
"gender" : "Male",
"emergencyContactPerson" : {
"name" : "Father",
"mobile" : "9412345678",
"email" : "example#gmail.com",
},
},
"contact" : {
"emailID" : {
"isVerified" : true,
"isChecked" : false,
"verificationTokenExpiresIn" : ISODate("2016-08-01T05:35:00.218Z"),
"verifiedOn" : ISODate("2016-08-01T04:35:10.992Z")
},
"mobileID" : {
"isVerified" : true,
"isChecked" : false,
"verificationTokenExpiresIn" : ISODate("2016-08-01T04:42:45.206Z"),
"verifiedOn" : ISODate("2016-08-01T04:33:36.692Z")
}
},
"services" : [
{
"applied" : true,
"appliedOn" : ISODate("2016-09-17T03:01:49.829Z"),
"status" : "Created",
"mac" : "70-77-88-00-AA-BB",
"createdBy" : "Example"
},
]
}
How can I build query, to get student info with the help of mac address 70-77-88-00-AA-BB. i only know mac address value?
i am new here please help me out
Query
services.mac is an array of all the mac addresses members of services
in querying(not in aggregation $eq) an array is equal with a value if it contains that value, so the above will work
the bellow query returns all the students, that have that mac adrress on the services array
if you want to make it fast you can also create an index on "services.mac"
*read mongodb documentation its very good and with examples
Test code here
db.collection.find({
"services.mac": "70-77-88-00-AA-BB"
})

sort a collection based on multiple fields in mongodb

I've a requirement where I need to sort the collection based on different fields. Below is my db entry
db.requests.find()
{ "_id" : ObjectId("5caf805f50ca58361589924b"),"type" : "adhoc", "immediate" : false, "place": "london"}
{ "_id" : ObjectId("5c947e37015bfe78a80e5349"),"type" : "adhoc", "immediate" : true, "place": "tokoy" }
{ "_id" : ObjectId("5c9481fa015bfe78a80e534d"),"type" : "periodic", "immediate" : false , "place": "bangalore"}
{ "_id" : ObjectId("5c94ae95015bfe78a80e5363"),"type" : "adhoc", "immediate" : true, "place": "lanka"}
{ "_id" : ObjectId("5c875a96015bfe7b5e772ea3"),"type" : "adhoc", "immediate" : false, "place": "jakarta"}
{ "_id" : ObjectId("5c9481fa015bfe78a80e534d"),"type" : "periodic", "immediate" : false , "place": "europe"}
considering
If "type" is "adhoc" then "immediate" can be either "true" or "false".
If "type" is "periodic" then "immediate" will always be "false"
I just want to have result in the below order:
all entries with "immediate" : "true"
all entries with "type": "adhoc" and "immediate": "false"
all entries with "type":"periodic"
Result should be like:
{ "_id" : ObjectId("5c947e37015bfe78a80e5349"),"type" : "adhoc", "immediate" : true, "place": "tokoy" }
{ "_id" : ObjectId("5c94ae95015bfe78a80e5363"),"type" : "adhoc", "immediate" : true, "place": "lanka"}
{ "_id" : ObjectId("5caf805f50ca58361589924b"),"type" : "adhoc", "immediate" : false, "place": "london"}
{ "_id" : ObjectId("5c875a96015bfe7b5e772ea3"),"type" : "adhoc", "immediate" : false, "place": "jakarta"}
{ "_id" : ObjectId("5c9481fa015bfe78a80e534d"),"type" : "periodic", "immediate" : false , "place": "bangalore"}
{ "_id" : ObjectId("5c9481fa015bfe78a80e534d"),"type" : "periodic", "immediate" : false , "place": "europe"}

Search Mongo Document based on BSON DateTime

My mongo document looks like below -
{
"_id" : ObjectId("5977dab66ea64e345288ceec"),
"transactionid" : "1",
"servicename" : "Reservation Service",
"starttime" : {
"dateTime" : true,
"symbol" : false,
"javaScriptWithScope" : false,
"string" : false,
"regularExpression" : false,
"javaScript" : false,
"double" : false,
"document" : false,
"DBPointer" : false,
"number" : false,
"boolean" : false,
"null" : false,
"bsonType" : "DATE_TIME",
"array" : false,
"int32" : false,
"int64" : false,
"binary" : false,
"value" : NumberLong(1501026996822),
"decimal128" : false,
"objectId" : false,
"timestamp" : false
},
"endtime" : {
"dateTime" : true,
"symbol" : false,
"javaScriptWithScope" : false,
"string" : false,
"regularExpression" : false,
"javaScript" : false,
"double" : false,
"document" : false,
"DBPointer" : false,
"number" : false,
"boolean" : false,
"null" : false,
"bsonType" : "DATE_TIME",
"array" : false,
"int32" : false,
"int64" : false,
"binary" : false,
"value" : NumberLong(1501026997875),
"decimal128" : false,
"objectId" : false,
"timestamp" : false
},
"status" : "Success",
"updatedby" : "muf",
"requestpayload" : "{\n \"service_header\": {\n \t\n \n \t\"service_name\": \"Reservation Service\",\n \t\"source_id\": \"Amex\",\n \t \t\"document_id\":\"1\",\n \t\"transaction_id\":\"1\"\n },\n \t\n \t\"airline\":\"united\",\n\t\"destination\":\"LAX\"\n\n\n}",
"responsepayload" : "[{\"departureDate\":\"2015/02/11\",\"airlineName\":\"United\",\"destination\":\"LAX\",\"price\":345.99,\"planeType\":\"Boeing 737\",\"code\":\"ER45if\",\"origin\":\"MUA\",\"emptySeats\":52},{\"departureDate\":\"2015/04/11\",\"airlineName\":\"United\",\"destination\":\"LAX\",\"price\":346.0,\"planeType\":\"Boeing 777\",\"code\":\"ER45jd\",\"origin\":\"MUA\",\"emptySeats\":12},{\"departureDate\":\"2015/06/11\",\"airlineName\":\"United\",\"destination\":\"LAX\",\"price\":423.0,\"planeType\":\"Boeing 707\",\"code\":\"ER0945\",\"origin\":\"MUA\",\"emptySeats\":0}]",
"exception" : "",
"requesthost" : "localhost",
"requestport" : "8086",
"requestpath" : "/flights"
}
I am trying to query below document using below query -
db.getCollection('Transaction').find({ starttime: { "$gt" : { "$date" : (new ISODate("2018-07-25T23:56:36.822Z")*1) } } })
I do get the result. However when I try to use less than and greater than together I don't get any result. I am not sure what is best way to query above document.
db.getCollection('Transaction').find({ starttime: { "$gt" : { "$date" : (new ISODate("2015-07-25T23:56:36.822Z")*1) } , "$lt" : { "$date" : (new ISODate("2018-07-25T23:56:36.822Z")*1) } } })

Modifying or Unwinding deep nested arrays with mongo query

After having made my own aggregation pipeline, I have arrived at the following result:
[
{
"_id": "53712c7238b8d900008ef71c",
"address": [
{
"_id": "53712c7238b8d900008ef71b",
"phoneNumber": "4092348294",
...
}
],
"name": "TestDealer",
"vehicles": [
{
"_id": "53712fa138b8d900008ef720",
"createdAt": "2014-05-12T20:08:00.000Z",
"tags": [
"vehicle"
],
"opts": [
{
"_id": "53712fa138b8d900008ef71e",
"hasSunroof": false,
...
}
],
"listed": true,
"disclosures": [
{
"_id": "53712fa138b8d900008ef71f",
"waterDamage": false,
...
}
],
"details": [
{
"_id": "53712fa138b8d900008ef71d",
"year": 2007,
...
}
]
},
{
"_id": "5373c6439058859af7904a17",
"createdAt": "2014-05-14T19:17:00.000Z",
"tags": [
"vehicle"
],
"opts": [
{
"_id": "5373c6439058859af7904a15",
"hasSunroof": false,
....
"other": []
}
],
"listed": true,
"disclosures": [
{
"_id": "5373c6439058859af7904a16",
"waterDamage": false,
...
}
],
"details": [
{
"_id": "5373c6439058859af7904a14",
"year": 2013,
...
}
]
}
]
}
]
As you can see, vehicles is an array of subdocuments (vehicles) that follow a specific schema:
details: an array of details subdocs
opts: an array of opts subdocs
disclosures: an array of disclosures subdocs
For each of details, disclosures and opts I would like to return the first subdoc in the array as opposed to an array. However, I'm not sure where to start. I can't really $unwind vehicles because it is possible that it might be empty.
Here's is what my final data should look like:
[
{
"_id": "53712c7238b8d900008ef71c",
"address": [
{
"_id": "53712c7238b8d900008ef71b",
"phoneNumber": "4092348294",
...
}
],
"name": "TestDealer",
"vehicles": [
{
"_id": "53712fa138b8d900008ef720",
"createdAt": "2014-05-12T20:08:00.000Z",
"tags": [
"vehicle"
],
"opts": {
"_id": "53712fa138b8d900008ef71e",
"hasSunroof": false,
...
},
"listed": true,
"disclosures": {
"_id": "53712fa138b8d900008ef71f",
"waterDamage": false,
...
},
"details": {
"_id": "53712fa138b8d900008ef71d",
"year": 2007,
...
}
},
{
"_id": "5373c6439058859af7904a17",
"createdAt": "2014-05-14T19:17:00.000Z",
"tags": [
"vehicle"
],
"opts": {
"_id": "5373c6439058859af7904a15",
"hasSunroof": false,
....
"other": []
},
"listed": true,
"disclosures": {
"_id": "5373c6439058859af7904a16",
"waterDamage": false,
...
},
"details": {
"_id": "5373c6439058859af7904a14",
"year": 2013,
...
}
}
]
}
]
EDIT:
Here is the aggregation I do to get my data (in CoffeeScript):
{
$match:
_id: ObjectId(params.id)
}
{
$unwind: '$inventories'
}
{
$match:
'inventories._id': 'active'
}
{
$redact:
$cond:
if:
$eq:['$listed',false]
then: '$$PRUNE'
else: '$$DESCEND'
}
{
$project:
address: 1
name: '$dealerName'
email: '$_id.email'
vehicles: '$inventories.vehicles'
}
As well as the original data:
{ "_id" : ObjectId( "53712c7238b8d900008ef71c" ),
"email" : "test#test.com",
"createdAt" : Date( 1399925280000 ),
"password" : "$2a$10$3dhicJuONkXeI9mQflXF0.JftAx7mLQaY2./6a3O7xdrs5qfH2zMW",
"firstName" : "TestName",
"lastName" : "testName",
"dealerName" : "TestDealer",
"dealerType" : "Franchised Dealer",
"emailIsVerified" : false,
"lastLoggedInAt" : Date( 1400247300000 ),
"expiresAt" : Date( 4524062882000 ),
"deletedAt" : null,
"updatedAt" : Date( 1400251500000 ),
"inventories" : [
{ "title" : "activeInventory",
"_id" : "active",
"vehicles" : [
{ "_id" : ObjectId( "53712fa138b8d900008ef720" ),
"createdAt" : Date( 1399925280000 ),
"tags" : [
"vehicle" ],
"opts" : [
{ "_id" : ObjectId( "53712fa138b8d900008ef71e" ),
"hasSunroof" : false,
"hasSnowTires" : false,
"hasPowerWindows" : false,
"hasNavigationSystem" : false,
"hasManuals" : false,
"hasMags" : false,
"hasLeather" : false,
"hasKeylessEntry" : false,
"hasHeatedSeats" : false,
"hasDvdSystem" : false,
"hasAirConditioning" : false,
"has2SetsOfKeys" : false,
"other" : [] } ],
"listed" : true,
"disclosures" : [
{ "_id" : ObjectId( "53712fa138b8d900008ef71f" ),
"waterDamage" : false,
"vehicleLien" : false,
"usVehicle" : false,
"totalLossByInsurer" : false,
"theftOrRecovery" : false,
"taxiOrLimo" : false,
"structuralPartsAreDamagedOrAlteredOrRepaired" : false,
"suspensionOrSubFrameNeedsRepair" : false,
"repainted" : false,
"previousDamageExceeding3k" : false,
"powerTrainNeedsRepair" : false,
"policeCruiser" : false,
"outOfProvinceOrState" : false,
"originalOwner" : false,
"originalManufacturerVinPlate" : false,
"originalSpecificationsChanged" : false,
"odometerRolledBackOrReplaced" : false,
"manufacturerWarrantyCancelled" : false,
"manufacturerBadgesChanged" : false,
"fuelSystemNeedsRepair" : false,
"fireDamage" : false,
"engineNeedsRepair" : false,
"emergencyVehicle" : false,
"electricalSystemNeedsRepair" : false,
"dailyRental" : false,
"computerNeedsRepair" : false,
"antiLockBrakesDamagedOrInoperable" : false,
"airbagIsMissingOrInoperable" : false,
"airConditioningNeedsRepair" : false } ],
"details" : [
{ "_id" : ObjectId( "53712fa138b8d900008ef71d" ),
"year" : 2007,
"vin" : "JN8AZ08W27W649264",
"trim" : "SE",
"transmission" : "Automatic",
"price" : 132123,
"model" : "Murano 4D Utility AWD",
"mileageReading" : 125000,
"make" : "Nissan",
"interiorColor" : "Black",
"history" : "Carproof Verified ($40.00)",
"hasAccident" : false,
"fuelType" : "Biodiesel",
"exteriorColor" : "Blue",
"driveTrain" : "FWD",
"description" : "dsadas",
"cylinders" : 4,
"mileageType" : "kms" } ] },
{ "_id" : ObjectId( "53713bfc1429925f0faf79d0" ),
"createdAt" : Date( 1399929780000 ),
"tags" : [
"vehicle" ],
"opts" : [
{ "_id" : ObjectId( "53713bfc1429925f0faf79ce" ),
"hasSunroof" : false,
"hasSnowTires" : false,
"hasPowerWindows" : false,
"hasNavigationSystem" : false,
"hasManuals" : false,
"hasMags" : false,
"hasLeather" : false,
"hasKeylessEntry" : false,
"hasHeatedSeats" : false,
"hasDvdSystem" : false,
"hasAirConditioning" : false,
"has2SetsOfKeys" : false,
"other" : [] } ],
"listed" : false,
"disclosures" : [
{ "_id" : ObjectId( "53713bfc1429925f0faf79cf" ),
"waterDamage" : false,
"vehicleLien" : false,
"usVehicle" : false,
"totalLossByInsurer" : false,
"theftOrRecovery" : false,
"taxiOrLimo" : false,
"structuralPartsAreDamagedOrAlteredOrRepaired" : false,
"suspensionOrSubFrameNeedsRepair" : false,
"repainted" : false,
"previousDamageExceeding3k" : false,
"powerTrainNeedsRepair" : false,
"policeCruiser" : false,
"outOfProvinceOrState" : false,
"originalOwner" : false,
"originalManufacturerVinPlate" : false,
"originalSpecificationsChanged" : false,
"odometerRolledBackOrReplaced" : false,
"manufacturerWarrantyCancelled" : false,
"manufacturerBadgesChanged" : false,
"fuelSystemNeedsRepair" : false,
"fireDamage" : false,
"engineNeedsRepair" : false,
"emergencyVehicle" : false,
"electricalSystemNeedsRepair" : false,
"dailyRental" : false,
"computerNeedsRepair" : false,
"antiLockBrakesDamagedOrInoperable" : false,
"airbagIsMissingOrInoperable" : false,
"airConditioningNeedsRepair" : false } ],
"details" : [
{ "_id" : ObjectId( "53713bfc1429925f0faf79cd" ),
"year" : 2007,
"vin" : "JN8AZ08W27W649264",
"trim" : "SE",
"transmission" : "Manual",
"price" : 13241234,
"model" : "Murano 4D Utility AWD",
"mileageReading" : 1312312,
"make" : "Mercedes-Benz",
"interiorColor" : "Black",
"history" : "Carproof Claims ($25.00)",
"hasAccident" : true,
"fuelType" : "Diesel",
"exteriorColor" : "Black",
"driveTrain" : "RWD",
"description" : "werwe",
"cylinders" : 4,
"mileageType" : "kms" } ] },
{ "_id" : ObjectId( "5373c6439058859af7904a17" ),
"createdAt" : Date( 1400095020000 ),
"tags" : [
"vehicle" ],
"opts" : [
{ "_id" : ObjectId( "5373c6439058859af7904a15" ),
"hasSunroof" : false,
"hasSnowTires" : false,
"hasPowerWindows" : false,
"hasNavigationSystem" : false,
"hasManuals" : false,
"hasMags" : false,
"hasLeather" : false,
"hasKeylessEntry" : false,
"hasHeatedSeats" : false,
"hasDvdSystem" : false,
"hasAirConditioning" : false,
"has2SetsOfKeys" : false,
"other" : [] } ],
"listed" : true,
"disclosures" : [
{ "_id" : ObjectId( "5373c6439058859af7904a16" ),
"waterDamage" : false,
"vehicleLien" : false,
"usVehicle" : false,
"totalLossByInsurer" : false,
"theftOrRecovery" : false,
"taxiOrLimo" : false,
"structuralPartsAreDamagedOrAlteredOrRepaired" : false,
"suspensionOrSubFrameNeedsRepair" : false,
"repainted" : false,
"previousDamageExceeding3k" : false,
"powerTrainNeedsRepair" : false,
"policeCruiser" : false,
"outOfProvinceOrState" : false,
"originalOwner" : false,
"originalManufacturerVinPlate" : false,
"originalSpecificationsChanged" : false,
"odometerRolledBackOrReplaced" : false,
"manufacturerWarrantyCancelled" : false,
"manufacturerBadgesChanged" : false,
"fuelSystemNeedsRepair" : false,
"fireDamage" : false,
"engineNeedsRepair" : false,
"emergencyVehicle" : false,
"electricalSystemNeedsRepair" : false,
"dailyRental" : false,
"computerNeedsRepair" : false,
"antiLockBrakesDamagedOrInoperable" : false,
"airbagIsMissingOrInoperable" : false,
"airConditioningNeedsRepair" : false } ],
"details" : [
{ "_id" : ObjectId( "5373c6439058859af7904a14" ),
"year" : 2013,
"vin" : "12345678901234567",
"trim" : "SE",
"transmission" : "Automatic",
"price" : 13564,
"model" : "Red",
"mileageReading" : 13453,
"make" : "Daihatsu",
"interiorColor" : "Black",
"history" : "Carproof Verified ($40.00)",
"hasAccident" : true,
"fuelType" : "Diesel",
"exteriorColor" : "Black",
"driveTrain" : "FWD",
"description" : "wrw",
"cylinders" : 3,
"mileageType" : "kms" } ] } ],
"tags" : [
"inventory",
"active",
"vehicles" ] },
{ "title" : "soldInventory",
"_id" : "sold",
"vehicles" : [],
"tags" : [
"inventory",
"sold",
"vehicles" ] },
{ "title" : "deletedInventory",
"_id" : "deleted",
"vehicles" : [],
"tags" : [
"inventory",
"deleted",
"vehicles" ] } ],
"address" : [
{ "_id" : ObjectId( "53712c7238b8d900008ef71b" ),
"phoneNumber" : "4092348294",
"country" : "Canada",
"zip" : "301111",
"region" : "Quebec",
"city" : "Montreal",
"street2" : "Apt. 101",
"street1" : "1213 Street",
"additionalNumbers" : [] } ],
"__v" : 3 }
If you are using 2.6 (which you must be since you use $redact) and if the array is always guaranteed to be empty if there are no tags or opts, you can use this technique to make sure you don't lose vehicles which have empty arrays when you $unwind:
In a $project phase add the following for all arrays you want to $unwind to keep just the first element:
opts:{$cond:{if:{$eq:[{$size:"$opts"},0]}, then:{$literal:[ "none" ]}, else:"$opts"}}
For each sub-array you can now group keeping the first one, and then repeat again for the next sub-array.
You'll need to be careful about unwinding and re-grouping for each array separately to keep from ending up with any duplication, if you are not aggregating anything else, you can do it in a single group with as many $unwinds as there are sub-arrays.

Passing More than one where condition in MONGO DB find query

I am having mongo DB collection namely student with the following document structure,
name:details:date:values
so, for an single name we will have one details list,
That details list will have multiple date lists
And each date list will have multiple values list
{
"_id" : ObjectId("51472e9fd29a736d83c27ca3"),
"name" : "Arun",
"details" : [
{
"date" : "2015-01-17",
"isNew" : false,
"isOld" : true,
"values" : [
{
"money" : "330.0",
"new" : false,
"old" : true,
},
{
"money" : "340.0",
"new" : false,
"old" : true,
}
]
},
{
"date" : "2015-01-17",
"isNew" : false,
"isOld" : false,
"values" : [
{
"money" : "330.0",
"new" : false,
"old" : false,
},
{
"money" : "340.0",
"new" : false,
"old" : false,
}
]
},
{
"date" : "2015-01-17",
"isNew" : true,
"isOld" : false,
"values" : [
{
"money" : "330.0",
"new" : true,
"old" : false,
},
{
"money" : "340.0",
"new" : true,
"old" : false,
}
]
},
{
"date" : "2013-10-19",
"isNew" : true,
"isOld" : false,
"values" : [
{
"money" : "330.0",
"new" : true,
"old" : false,
},
{
"money" : "340.0",
"new" : true,
"old" : false,
}
]
}
]
}
What is need is, i want to SELECT "all the date lists" where "name" : "Arun" and "date" : "2015-01-17",I tried this way and it is not working as expected.I am getting all the dates instead 2015-01-17 in return.
I think only one where condition is working here and that is "name" : "Arun" , Query is not considering "details.date" : "2015-01-17" in where condition.
db.student.find({ "details.date" : "2015-01-17","name" : "Arun" },{"details.date":1}).pretty()
{
"_id" : ObjectId("51472e9fd29a736d83c27ca3"),
"details" : [
{
"date" : "2015-01-17"
},
{
"date" : "2015-01-17"
},
{
"date" : "2015-01-17"
},
{
"date" : "2013-10-19"
}
]
}
I am currently using mongo 1.6.5
Can some one help me to solve this.?
First, you need to upgrade to a current version of MongoDB. 1.6 is now three versions behind the current "major" version.
Second, you need to fix your schema. You say "for an single name we will have one details list" - if you continue adding things into this list/array it will continue growing indefinitely and that's a bad schema design. In addition, it's more correct to group in an array values that you want to fetch together with the document - and in this case you specifically do NOT want to fetch all the values with the document, you only want to fetch an element for a particular date, plus the isOld/isNew fields suggest to me that some of these entries will correspond to out-dated values, and others will be current, and it's a bad idea to lump them together into the same document.
So my recommendation is to change your structure to be multiple documents for each student:
{
"name" : "Arun",
"date" : "2015-01-17",
"isNew" : false,
"isOld" : true,
"values" : [
{
"money" : "330.0",
"new" : false,
"old" : true,
},
{
"money" : "340.0",
"new" : false,
"old" : true,
}
]
},
{
"name" : "Arun",
"date" : "2015-01-17",
"isNew" : false,
"isOld" : true,
"values" : [
{
"money" : "330.0",
"new" : false,
"old" : false,
},
{
"money" : "340.0",
"new" : false,
"old" : false,
}
]
},
{
"name" : "Arun",
"date" : "2015-01-17",
"isNew" : false,
"isOld" : true,
"values" : [
{
"money" : "330.0",
"new" : true,
"old" : false,
},
{
"money" : "340.0",
"new" : true,
"old" : false,
}
]
},
{ "name" : "Arun",
"date" : "2013-10-19",
"isNew" : true,
"isOld" : false,
"values" : [
{
"money" : "330.0",
"new" : true,
"old" : false,
},
{
"money" : "340.0",
"new" : true,
"old" : false,
}
]
}
]
}
Now it'll be much more straight forward to query on various attributes, including being able to query in values as well as outer fields.
Your query is in fact matching both fields. The output is a byproduct of how MongoDB handles arrays. Matching against
"details.date" : "2015-01-17"
will return any documents in the collection where any of the entries from the details field have the right date. It will not just return the individual entries from the details array.
To do this, you may want to look at the $elemMatch operator for projection, to limit the entries in the array that are returned.
Here is your query,
db.sandy.aggregate(
{$unwind : "$details"},
{$match : {"details.date" : "2015-01-17","name" : "Arun"}}
)
And I guess mongo 1.6.5 does not support aggregation. refer to Doc once.