How to get size of the syllabus array

{
	"_id" : ObjectId("606b7031a0ccf722226a85ae"),
	"groupId" : ObjectId("5f06cca74e51ba15f5167b86"),
	"insertedAt" : "2021-04-05T20:16:49.893343Z",
	"isActive" : true,
	"staffId" : [
		"606b6b44a0ccf72222ce375a"
	],
	"subjectName" : "English",
	"teamId" : ObjectId("6069a6a9a0ccf704e7f4b537"),
	"updatedAt" : "2021-04-05T20:16:49.893382Z",
	"syllabus" : [
		{
			"chapterId" : "627f4e05ae6cd20cefbe3bb1",
			"chapterName" : "chap1",
			"topicsList" : [
				{
					"topicId" : "627f4e05ae6cd20cefbe3bb2",
					"topicName" : "1.1"
				},
				{
					"topicId" : "627f4e05ae6cd20cefbe3bb3",
					"topicName" : "2.5"
				}
			]
		},
		{
			"chapterId" : "627f4e05ae6cd20cefbe3bb4",
			"chapterName" : "chap2",
			"topicsList" : [
				{
					"topicId" : "627f4e05ae6cd20cefbe3bb5",
					"topicName" : "1"
				},
				{
					"topicId" : "627f4e05ae6cd20cefbe3bb6",
					"topicName" : "2"
				}
			]
		}
	],
	"updateAt" : "2022-05-14T06:36:53.981765Z"
}

mongo query

db.subject_staff_database.aggregate({$project: { numberOfCourses: { $size: "$syllabus" }}})

Result

uncaught exception: Error: command failed: {
	"ok" : 0,
	"errmsg" : "The argument to $size must be an array, but was of type: missing",
	"code" : 17124,
	"codeName" : "Location17124"
} : aggregate failed :

In your case, the syllabus property might be missing in the document so only the issue is coming.

db.subject_staff_database.aggregate([{$project: {
numberOfCourses :{$cond: [{$ne: [{$type:’$syllabus’}, ‘missing’]}, {$size :’$syllabus’}, 0 ]}
}}])

Thanks a lot Sudhesh_Gnanasekaran the query is working fine

1 Like

There is an issue with the query.

Consider the following documents:

{ _id: 0, syllabus: 369 }
{ _id: 1, syllabus: [ 369 ] }
{ _id: 2 }

The query will work fine with _id:1 and _id:2 but will fail with _id:0. This case seems to be absent from your data since

The following variation will work in all the cases.

db.subject_staff_database.aggregate([{$project: {
numberOfCourses :{$cond: [{$eq: [{$type:"$syllabus"}, "array"]}, {$size :"$syllabus"}, 0 ]}
}}])

The difference being

{$eq: [{$type:"$syllabus"}, "array"]}

vs

{$ne: [{$type:"$syllabus"}, "missing"]}

@Sudhesh_Gnanasekaran, please read Formatting code and log snippets in posts before posting your next code snippet. This will ensure we can cut-n-paste your query and use it directly without editing the fancy html quotes we get when it is not marked up correctly.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.