Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am trying to generate a new collection with a field 'desc' having into account a condition in field in a documment array. To do so, I am using
$cond
statement
The origin collection example is the next one:
"_id" : ObjectId("5e8ef9a23e4f255bb41b9b40"),
"Brand" : {
"models" : [
"name" : "AA"
"name" : "BB"
"_id" : ObjectId("5e8ef9a83e4f255bb41b9b41"),
"Brand" : {
"models" : [
"name" : "AG"
"name" : "AA"
The query is the next:
db.runCommand({
aggregate: 'cars',
'pipeline': [
'$project': {
'desc': {
'$cond': {
if: {
$in: ['$Brand.models.name',['BB','TC','TS']]
then: 'Good',
else: 'Bad'
'$project': {
'desc': 1
$out: 'cars_stg'
'allowDiskUse': true,
The problem is that the $cond statement is always returning the "else" value. I also have tried $or statement with $eq or the $and with $ne, but is always returning "else".
What am I doing wrong, or how should I fix this?
Thanks
Since $Brand.models.name returns an array, we cannot use $in operator.
Instead, we can use $setIntersection which returns an array that contains the elements that appear in every input array
db.cars.aggregate([
"$project": {
"desc": {
"$cond": [
$gt: [
$size: {
$setIntersection: [
"$Brand.models.name",
"BB",
"TC",
"Good",
"Bad"
"$project": {
"desc": 1
$out: 'cars_stg'
MongoPlayground | Alternative $reduce
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.