Positional operator $ updating wrong nested doc in mongodb - mongodb

I have a collections
users
{
"_id" : ObjectId("53738eb7ac8ee07007c1d75a"),
"first" : "Shivam",
"connections" : [
{
"invit_made" : [ ],
"fl_no" : 615,
"date" : ISODate("2014-05-16T00:00:00Z"),
"fl" : "LB",
"TYP" : "ZLP",
"invit_reciv" : [ ],
},
{
"invit_made" : [ ],
"fl_no" : 615,
"date" : ISODate("2014-05-20T00:00:00Z"),
"fl" : "LB",
"invit_reciv" : [ ],
"TYP" : "ZLP",
}
]
}
I am performing update accoding to date in connections.but wrong nested documented is updated in my case.
db.users.update(
{ 'connections.TYP' : 'ZLP'
,'connections.fl' : 'LB'
,'connections.date' : ISODate("2014-05-20T00:00:00Z")
},
{ '$addToSet' : {
'connections.$.invit_reciv' : { 'last' : 'abc'}
}
})
Actual Result I am getting.
{
"_id" : ObjectId("53738eb7ac8ee07007c1d75a"),
"first" : "Shivam",
"connections" : [
{
"invit_made" : [ ],
"fl_no" : 615,
"date" : ISODate("2014-05-16T00:00:00Z"),
"fl" : "LB",
"TYP" : "ZLP",
"invit_reciv" : [
{
"last" : "abc"
}
],
},
{
"invit_made" : [ ],
"fl_no" : 615,
"date" : ISODate("2014-05-20T00:00:00Z"),
"fl" : "LB",
"invit_reciv" : [ ],
"TYP" : "ZLP",
}
]
}
Result I expect
{
"_id" : ObjectId("53738eb7ac8ee07007c1d75a"),
"first" : "Shivam",
"connections" : [
{
"invit_made" : [ ],
"fl_no" : 615,
"date" : ISODate("2014-05-16T00:00:00Z"),
"fl" : "LB",
"TYP" : "ZLP",
"invit_reciv" : [ ],
},
{
"invit_made" : [ ],
"fl_no" : 615,
"date" : ISODate("2014-05-20T00:00:00Z"),
"fl" : "LB",
"invit_reciv" : [
{
"last" : "abc"
}
],
"TYP" : "ZLP",
}
]
}
Please help me understand what is happening in present query and what is wrong with it.

You should use $elemMatch with positional operator, it allows you to match specific nested doc:
db.users.update(
{ connections:{
$elemMatch:{
'TYP' : 'ZLP',
'fl' : 'LB',
'date' : ISODate("2014-05-20T00:00:00Z")
}
}
},
{ '$addToSet' : {
'connections.$.invit_reciv' :
{ 'last' : 'abc'}
}
}
)

Related

$map upto three nested array mongodb aggregation

I´m facing a challenge here. I have this collection here
{
"_id" : ObjectId("5e0ff6d424f9fc12bc3d9464"),
"name" : "Pizzaria Don Juan",
"active" : true,
"branches" : [
{
"location" : {
"type" : "Point",
"coordinates" : [ ]
},
"_id" : ObjectId("5e19cafc31d60216b8dbd649"),
"name" : "Parque da Mooca",
"address" : "Rua Dianópolis",
"addressNumber" : 1283,
"federalId" : "10.445.089/0001-44",
"complement" : "Ap 55",
"postalCode" : "03126-007",
"coveredArea" : 0,
"neighborhood" : "Parque da Mooca",
"deliveryTime" : 0,
"deliveryRate" : 0,
"standard" : false,
"city" : "Mococa",
"state" : "RJ",
"emails" : [ ],
"phones" : [ ],
"daysWeek" : [ ],
"socialMedias" : [ ],
"paymentTerms" : [ ],
"sections" : [ ]
},
{
"location" : {
"type" : "Point",
"coordinates" : [ ]
},
"_id" : ObjectId("5e19c9a531d60216b8dbd639"),
"name" : "Principal",
"address" : "Rua Nicolau Filizola",
"addressNumber" : null,
"federalId" : "10.445.089/0001-53",
"complement" : "",
"postalCode" : "05547-010",
"coveredArea" : 0,
"neighborhood" : "Jardim Rosa Maria",
"deliveryTime" : 0,
"deliveryRate" : 0,
"standard" : true,
"city" : "São Paulo",
"state" : "SP",
"emails" : [
{
"_id" : ObjectId("5e19ca9531d60216b8dbd643"),
"name" : "Contato",
"address" : "contato#pizzariadonjuan.com.br"
},
{
"_id" : ObjectId("5e19ca9531d60216b8dbd642"),
"name" : "Contato2",
"address" : "contato2#pizzariadonjuan.com.br"
}
],
"phones" : [
{
"_id" : ObjectId("5e19ca9531d60216b8dbd645"),
"name" : "Principal",
"number" : "(11) 99740-2216"
},
{
"_id" : ObjectId("5e19ca9531d60216b8dbd644"),
"name" : "Secundario",
"number" : "(11) 2562-2759"
}
],
"daysWeek" : [
{
"_id" : ObjectId("5e1cf99741c52d4a587a9162"),
"startsAt" : 64800000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a124a17fd054900a1afb2")
},
{
"_id" : ObjectId("5e1cf99741c52d4a587a9161"),
"startsAt" : 0,
"endsAt" : 0,
"opens" : false,
"dayWeekId" : ObjectId("5e1a126817fd054900a1afb3")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a9170"),
"startsAt" : 64980000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a126e17fd054900a1afb4")
},
{
"_id" : ObjectId("5e1b8fac96516432845e364c"),
"startsAt" : 64980000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a127517fd054900a1afb5")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a916f"),
"startsAt" : 64980000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a127a17fd054900a1afb6")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a916e"),
"startsAt" : 64800000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a23f8bf353f493c74e8ae")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a916d"),
"startsAt" : 61380000,
"endsAt" : 83154000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a2407bf353f493c74e8af")
}
],
"socialMedias" : [
{
"_id" : ObjectId("5e1d082641c52d4a587a9191"),
"socialMediaId" : ObjectId("5e10089a3330ad05d4e1867d"),
"url" : "rewrwerwerwerwerwerwerwer"
}
],
"paymentTerms" : [
{
"_id" : ObjectId("5e1d143041c52d4a587a91b7"),
"paymentTermId" : ObjectId("5e1a2277bf353f493c74e8a7")
},
{
"_id" : ObjectId("5e1d143041c52d4a587a91b6"),
"paymentTermId" : ObjectId("5e1a228cbf353f493c74e8a8")
},
{
"_id" : ObjectId("5e1d143041c52d4a587a91b5"),
"paymentTermId" : ObjectId("5e1a229ebf353f493c74e8a9")
}
],
"sections" : [
{
"_id" : ObjectId("5e1e535441c52d4a587a9208"),
"name" : "Camisetas",
"products" : [
{
"_id" : ObjectId("5e1e662f044582129844ffd5"),
"name" : "DonJuan M",
"description" : "",
"quantityAvailable" : 0,
"image" : "",
"price" : 0,
"validFrom" : ISODate("2020-01-15T01:08:49.552Z"),
"validTo" : ISODate("2020-01-15T01:08:49.552Z"),
"enabled" : true
}
]
},
{
"_id" : ObjectId("5e20ec889c05f229a484ea3d"),
"name" : "Imãs",
"products" : [
{
"_id" : ObjectId("5e20ec889c05f229a484ea3e"),
"name" : "Imã",
"description" : "Imã",
"quantityAvailable" : 0,
"image" : "",
"price" : 0,
"validFrom" : ISODate("0001-01-01T00:00:00Z"),
"validTo" : ISODate("9999-12-31T00:00:00Z"),
"enabled" : true
}
]
}
]
}
],
"users" : [
{
"_id" : ObjectId("5e10fc2adc147a373c312144")
},
{
"_id" : ObjectId("5e11ff8003eb832ef84342a6")
}
],
"socialMedias" : [
{
"_id" : ObjectId("5e165672a2204b49c892db74"),
"socialMediaId" : ObjectId("5e10089a3330ad05d4e1867d"),
"url" : "uuuutt"
},
{
"_id" : ObjectId("5e15385fb3a0aa1004ac3598"),
"socialMediaId" : ObjectId("5e1009043330ad05d4e1867f"),
"url" : "jkkjkjkjkjk"
}
],
"sections" : [
{
"_id" : ObjectId("5e15313b2e985e16ec4e7413"),
"name" : "Bebidas",
"products" : [
{
"_id" : ObjectId("5e1e6381044582129844ffc2"),
"name" : "Coca Cola Zero 2 Litros",
"description" : "",
"quantityAvailable" : 0,
"image" : "",
"price" : 18.39,
"validFrom" : ISODate("1970-01-01T00:00:00Z"),
"validTo" : ISODate("1970-01-01T00:00:00Z"),
"enabled" : true
},
{
"_id" : ObjectId("5e1e6381044582129844ffc3"),
"name" : "Coca Cola 2 Litros",
"description" : "",
"quantityAvailable" : 0,
"image" : "",
"price" : 21.42,
"validFrom" : ISODate("1970-01-01T00:00:00Z"),
"validTo" : ISODate("1970-01-01T00:00:00Z"),
"enabled" : true
},
{
"_id" : ObjectId("5e1e662f044582129844ffda"),
"name" : "Cerveja Heineken Lata 350ml",
"description" : "Cerveja Heineken Lata 350ml",
"quantityAvailable" : 0,
"image" : "volkswagen-polo.jpg",
"price" : 1.55,
"validFrom" : ISODate("2020-01-01T00:00:00Z"),
"validTo" : ISODate("1970-01-01T00:00:00Z"),
"enabled" : true
}
]
},
{
"_id" : ObjectId("5e20e8de9c05f229a484ea27"),
"name" : "Esfihas",
"products" : [
{
"_id" : ObjectId("5e20e8de9c05f229a484ea28"),
"name" : "Esfiha de carne",
"description" : "Esfiha de carne",
"quantityAvailable" : 0,
"image" : "",
"price" : 5,
"validFrom" : ISODate("2020-01-01T00:00:00Z"),
"validTo" : null,
"enabled" : true
}
]
}
],
"__v" : 0
}
{
"_id" : ObjectId("5e0ffd23991918424c8d7c3b"),
"name" : "Pizza Ruth",
"active" : true,
"users" : [ ],
"socialMedias" : [ ],
"branches" : [ ],
"sections" : [ ],
"__v" : 0
}
{
"_id" : ObjectId("5e0ffd3d991918424c8d7c3c"),
"name" : "Feijão de Corda",
"active" : true,
"users" : [ ],
"socialMedias" : [ ],
"branches" : [ ],
"sections" : [ ],
"__v" : 0
}
The fields validFrom and validTo (Date fields) from the collection products nested in branches.sections need to be converted to the format yyyy-mm-dd. I can do that with this aggregation pipeline:
{ $unwind: { path: "$branches.sections", preserveNullAndEmptyArrays: true } },
{
"$addFields": {
"branches.sections.products": {
$map: {
input: "$branches.sections.products",
as: "product",
in: {
'_id': "$$product._id",
'name': "$$product.name",
'description': "$$product.description",
'quantityAvailable': "$$product.quantityAvailable",
'image': "$$product.image",
'imageUrl': "$$product.imageUrl",
'price': "$$product.price",
'validFrom' : {"$dateToString": { "date": "$$product.validFrom", "format": "%Y-%d-%m" }},
'validTo' : {"$dateToString": { "date": "$$product.validTo", "format": "%Y-%d-%m" }},
'enabled': "$$product.enabled",
}
}
}
}
}
I can successfully convert those date fields, but I need now to "re-unwind" the array products, in order to be just like before the unwind.
Any clue in how to proceed? Or even a different way to format those dates without having to unwind? Tried dozens of ways of $group, but without any success.
You just need to $map over each nested array to drill upload the validTo and validFrom field
.aggregate([
{ "$addFields": {
"branches": {
"$map": {
"input": "$branches",
"as": "branch",
"in": {
"$mergeObjects": [
"$$branch",
{ "section": {
"$map": {
"input": "$$branch.sections",
"as": "section",
"in": {
"$mergeObjects": [
"$$section",
{ "product": {
"$map": {
"input": "$$section.products",
"as": "product",
"in": {
"$mergeObjects": [
"$$product",
{
"validFrom": { "$dateToString": { "date": "$$product.validFrom", "format": "%Y-%d-%m" }},
"validTo": { "$dateToString": { "date": "$$product.validTo", "format": "%Y-%d-%m" }}
}
]
}
}
}}
]
}
}
}}
]
}
}
}
}}
])
MongoPlayground

Mongodb update nested array by id

I have the following document and want to update state
Document ID: ObjectId("5a4e5a448b70d50e34d204a5")
Target ID: ObjectId("5a4e5a438b70d50e34d203ea")
I have no idea how to update the state to e.g. 4
{
"_id" : ObjectId("5a4e5a448b70d50e34d204a5"),
"name" : "Wirtschaftsdienst",
"date" : ISODate("2012-10-07T00:00:00.000Z"),
"comment" : null,
"tasks" : [
{
"name" : "Speisen und Getränke",
"sections" : [
{
"start" : 46800,
"end" : 72000,
"entirely" : true,
"assistants" : [
{
"assistant" : {
"_id" : ObjectId("5a4e5a438b70d50e34d203ea")
},
"state" : 3
},
{
"assistant" : {
"_id" : ObjectId("5a4e5a438b70d50e34d203f4")
},
"state" : 3
}
]
}
]
}
]
}
Use positional operator $[] along with arrayFilters to get your job done!
Try this query:
db.collection.update(
{"_id" : ObjectId("5a4e5a448b70d50e34d204a5")},
{$set: {"tasks.$[].sections.$[].assistants.$[element].state":4}},
{arrayFilters: [ {"element.assistant":{"_id" :
ObjectId("5a4e5a438b70d50e34d203ea")} }
], multi:true}
)
And the output is:
/* 1 */
{
"_id" : ObjectId("5a4e5a448b70d50e34d204a5"),
"name" : "Wirtschaftsdienst",
"date" : ISODate("2012-10-07T00:00:00.000Z"),
"comment" : null,
"tasks" : [
{
"name" : "Speisen und Getränke",
"sections" : [
{
"start" : 46800,
"end" : 72000,
"entirely" : true,
"assistants" : [
{
"assistant" : {
"_id" : ObjectId("5a4e5a438b70d50e34d203ea")
},
"state" : 4.0
},
{
"assistant" : {
"_id" : ObjectId("5a4e5a438b70d50e34d203f4")
},
"state" : 3.0
}
]
}
]
}
]
}

get length of array via variable just created mongodb

I am new to mongodb, I have a dataset that looks like the following, and I'm trying to Write an aggregation query that will determine the number of unique companies with which an individual has been associated.
Schema:
{
"_id" : ObjectId("52cdef7c4bab8bd675297d8b"),
"name" : "AdventNet",
"permalink" : "abc3",
"crunchbase_url" : "http://www.crunchbase.com/company/adventnet",
"homepage_url" : "http://adventnet.com",
"blog_url" : "",
"blog_feed_url" : "",
"twitter_username" : "manageengine",
"category_code" : "enterprise",
"number_of_employees" : 600,
"founded_year" : 1996,
"deadpooled_year" : 2,
"tag_list" : "",
"alias_list" : "Zoho ManageEngine ",
"email_address" : "pr#adventnet.com",
"phone_number" : "925-924-9500",
"description" : "Server Management Software",
"created_at" : ISODate("2007-05-25T19:24:22Z"),
"updated_at" : "Wed Oct 31 18:26:09 UTC 2012",
"overview" : "<p>AdventNet is now Zoho ManageEngine.</p>\n\n<p>Founded in 1996, AdventNet has served a diverse range of enterprise IT, networking and telecom customers.</p>\n\n<p>AdventNet supplies server and network management software.</p>",
"image" : {
"available_sizes" : [
[
[
150,
55
],
"assets/images/resized/0001/9732/19732v1-max-150x150.png"
],
[
[
150,
55
],
"assets/images/resized/0001/9732/19732v1-max-250x250.png"
],
[
[
150,
55
],
"assets/images/resized/0001/9732/19732v1-max-450x450.png"
]
]
},
"products" : [ ],
"relationships" : [
{
"is_past" : true,
"title" : "CEO and Co-Founder",
"person" : {
"first_name" : "Sridhar",
"last_name" : "Vembu",
"permalink" : "sridhar-vembu"
}
},
{
"is_past" : true,
"title" : "VP of Business Dev",
"person" : {
"first_name" : "Neil",
"last_name" : "Butani",
"permalink" : "neil-butani"
}
},
{
"is_past" : true,
"title" : "Usabiliy Engineer",
"person" : {
"first_name" : "Bharath",
"last_name" : "Balasubramanian",
"permalink" : "bharath-balasibramanian"
}
},
{
"is_past" : true,
"title" : "Director of Engineering",
"person" : {
"first_name" : "Rajendran",
"last_name" : "Dandapani",
"permalink" : "rajendran-dandapani"
}
},
{
"is_past" : true,
"title" : "Market Analyst",
"person" : {
"first_name" : "Aravind",
"last_name" : "Natarajan",
"permalink" : "aravind-natarajan"
}
},
{
"is_past" : true,
"title" : "Director of Product Management",
"person" : {
"first_name" : "Hyther",
"last_name" : "Nizam",
"permalink" : "hyther-nizam"
}
},
{
"is_past" : true,
"title" : "Western Regional OEM Sales Manager",
"person" : {
"first_name" : "Ian",
"last_name" : "Wenig",
"permalink" : "ian-wenig"
}
}
],
"competitions" : [ ],
"providerships" : [
{
"title" : "DHFH",
"is_past" : true,
"provider" : {
"name" : "A Small Orange",
"permalink" : "a-small-orange"
}
}
],
"total_money_raised" : "$0",
"funding_rounds" : [ ],
"investments" : [ ],
"acquisition" : null,
"acquisitions" : [ ],
"offices" : [
{
"description" : "Headquarters",
"address1" : "4900 Hopyard Rd.",
"address2" : "Suite 310",
"zip_code" : "94588",
"city" : "Pleasanton",
"state_code" : "CA",
"country_code" : "USA",
"latitude" : 37.692934,
"longitude" : -121.904945
}
],
"milestones" : [ ],
"video_embeds" : [ ],
"screenshots" : [
{
"available_sizes" : [
[
[
150,
94
],
"assets/images/resized/0004/3400/43400v1-max-150x150.png"
],
[
[
250,
156
],
"assets/images/resized/0004/3400/43400v1-max-250x250.png"
],
[
[
450,
282
],
"assets/images/resized/0004/3400/43400v1-max-450x450.png"
]
],
"attribution" : null
}
],
"external_links" : [ ],
"partners" : [ ]
}
Here is the query I tried:
db.companies.aggregate([{
$match: {
"relationships.person": {
$ne: null
}
}
}, {
$project: {
relationships: 1,
_id: 0
}
}, {
$unwind: "$relationships"
}, {
$group: {
_id: "$relationships.person",
count: {
$addToSet: "$relationships"
}
}
}])
I think I now need to get the length of the $relationships array? How would I do that?
When you only want the size of the array you really don't need to unwind...
Just use $size.
Alter your aggregation to:
db.companies.aggregate([{
$match: {
"relationships.person": {
$ne: null
}
}
}, {
$project: {
relationships: 1,
_id: 0,
relationship_size : { $size : "$relationships"}
}
}
}])
This should give you the result you want
From the comment i understand you want some more logic in the aggregation, from outta my head i would alter your aggregation to:
db.companies.aggregate([{
$match: {
"relationships.person": {
$ne: null
}
}
}, {
$project: {
relationships: 1,
_id: 0
}
}, {
$unwind: "$relationships"
}, {
$group: {
_id: "$relationships.person.permalink",
count : {$sum : 1}
}
}])
I can't find a "company name" in your relationships array so i use the permalink property

mongodb select item from array, group them and count total

When I write like this
db.Profiles.find({ userId:4790, "p2l.listId":31618 }, { "p2l.$": 1 } )
I get the desired result
...
{
"_id" : ObjectId("56052d35df3e5e564f770ed0"),
"p2l" : [
{
"listId" : 31618,
"status" : 131
}
] }
{
"_id" : ObjectId("56052d25df3e5e564f770ecd"),
"p2l" : [
{
"listId" : 31618,
"status" : 25
}
] }
{
"_id" : ObjectId("56052d1adf3e5e564f770eca"),
"p2l" : [
{
"listId" : 31618,
"status" : 25
}
] }
{
"_id" : ObjectId("5603c882bd1f3d3668ba7352"),
"p2l" : [
{
"listId" : 31618,
"status" : 24
}
] }
, but I have to group it by status
How I can do it?
I try as
db.Profiles.aggregate( {$match:{ userId:4790, "p2l.listId":31618}},
{$project:{"p2l.listId":"$p2l.listId", "p2l.status":"$p2l.status"}} )
but in rezult, I have values, that do not meet the parameters of the request. As a result, there listId = 31617
{
"result" : [
...
{
"_id" : ObjectId("56052d25df3e5e564f770ecd"),
"p2l" : [
{
"listId" : [
31618
],
"status" : [
25
]
}
]
},
{
"_id" : ObjectId("56052d1adf3e5e564f770eca"),
"p2l" : [
{
"listId" : [
31618,
31617
],
"status" : [
25,
25
]
},
{
"listId" : [
31618,
31617
],
"status" : [
25,
25
]
}
]
},
{
"_id" : ObjectId("5603c882bd1f3d3668ba7352"),
"p2l" : [
{
"listId" : [
31618
],
"status" : [
24
]
}
]
}
],
"ok" : 1.0000000000000000,
"$gleStats" : {
"lastOpTime" : Timestamp(0, 0),
"electionId" : ObjectId("5606384b5e0803423d340427")
}
}
I found a solution, here's an example
db.Profiles.aggregate(
{ $match : {
"p2l.listId": 31618
}},
{ $unwind : "$p2l" },
{ $match : {
"p2l.listId": 31618
}},
{$project:{"p2l":"$p2l"}},
{$group:{_id : { "p2l.status": "$p2l.status"},
"count": { $sum: 1 }}}
)

Mongo:count the total number of elements in array depending on condition

I am new to mongoDB . I have aware of some basic queries of mongoDb but not advanced.
My document looks like following :
{
"_id" : ObjectId("5289deaa84aedcc100228259"),
"gender" : "male",
"intrest" : [
{
"userId" : ObjectId("5286294984ae18ac5d19af36"),
"timestamp" : ISODate("2013-11-18T09:32:38.040Z"),
"status" : "Pending"
},
{
"userId" : ObjectId("5286295984ae18ac5d19af37"),
"timestamp" : ISODate("2013-11-18T09:33:17.493Z"),
"status" : "Pending"
}
],
"intrestAccepted" : [ ],
"intrestCancled" : [ ],
"intrestDeclined" : [ ],
"intrestReceived" : [
ObjectId("5286294984ae18ac5d19af36"),
ObjectId("5286295984ae18ac5d19af37")
],
"owner" : ObjectId("5286293284ae18ac5d19af35"),
"postDesc" : "gggg",
"tags" : [
"ggg"
]
}
{
"_id" : ObjectId("5289dea084aedcc100228258"),
"gender" : "female",
"intrest" : [
{
"userId" : ObjectId("5286294984ae18ac5d19af36"),
"timestamp" : ISODate("2013-11-18T09:32:42.934Z"),
"status" : "Pending"
},
{
"userId" : ObjectId("5286295984ae18ac5d19af37"),
"timestamp" : ISODate("2013-11-18T09:33:18.520Z"),
"status" : "Pending"
}
],
"intrestAccepted" : [ ],
"intrestCancled" : [ ],
"intrestDeclined" : [ ],
"intrestReceived" : [
ObjectId("5286294984ae18ac5d19af36"),
ObjectId("5286295984ae18ac5d19af37")
],
"owner" : ObjectId("5286293284ae18ac5d19af35"),
"postDesc" : "asdf",
"tags" : [
"asdf"
]
}
{
"_id" : ObjectId("5289dec984aedcc10022825a"),
"gender" : "male",
"intrest" : [
{
"userId" : ObjectId("5286295984ae18ac5d19af37"),
"timestamp" : ISODate("2013-11-18T09:33:20.996Z"),
"status" : "Pending"
}
],
"intrestAccepted" : [ ],
"intrestCancled" : [ ],
"intrestDeclined" : [ ],
"intrestReceived" : [
ObjectId("5286295984ae18ac5d19af37")
],
"owner" : ObjectId("5286294984ae18ac5d19af36"),
"postDesc" : "fff",
"tags" : [
"fff"
]
}
I want to find totalcount for intrestReceived[] whose owner is ObjectId("5286293284ae18ac5d19af35")
What query am I supposed to write. Please help .
You could try something simple like this:
intrestReceived_length = 0
db.col.find({ _id: ObjectId("5286293284ae18ac5d19af35") }).forEach( function( doc ){
intrestReceived_length = doc.intrestReceived.length;
});
The find will extract only the document that matches the ObjectId you provided and then we use a forEach on the cursor to iterate over all of the (one) results. Within the forEach callback, we just use a JavaScript array.length command to extract the size of the array.
You could also output only the intrestReceived array by providing a projection in your find command:
db.col.find({ _id: ObjectId("5286293284ae18ac5d19af35") }, { "intrestReceived": 1 })...
This will return the same document but it will only contain the _id and intrestReceived attributes.