MongoDB query sample: using $unwind
This is the sample collection I am using in this example:
db.getCollection('testCol').find({}).pretty()
{
"_id" : ObjectId("59764121cd6857bf00a34809"),
"a" : 1,
"b" : 1
}
{
"_id" : ObjectId("59764126cd6857bf00a3480a"),
"a" : 2,
"b" : 2
}
{
"_id" : ObjectId("5976412ccd6857bf00a3480b"),
"a" : 3,
"b" : 3
}
{
"_id" : ObjectId("59764294cd6857bf00a3480c"),
"a" : 4,
"b" : 4,
"arr" : [
{
"a" : 6,
"b" : 6
},
{
"a" : 7,
"b" : 7
}
]
}
This will give me the number of element inside of the array:
db.getCollection('testCol').aggregate([{$match:{$and:[{a:{"$eq": 4}}]}},
{ $unwind : "$arr" },
{ $group: {
_id: '',
count: { $sum: 1 }}}
])
This was useful for me when I had to do count validation after loading data from Oracle (or any rdbms) into MongoDB when I am using a custom defined _id which isn't unique. We can push any entries with duplicated custom _id into array.
db.getCollection('testCol').find({}).pretty()
{
"_id" : ObjectId("59764121cd6857bf00a34809"),
"a" : 1,
"b" : 1
}
{
"_id" : ObjectId("59764126cd6857bf00a3480a"),
"a" : 2,
"b" : 2
}
{
"_id" : ObjectId("5976412ccd6857bf00a3480b"),
"a" : 3,
"b" : 3
}
{
"_id" : ObjectId("59764294cd6857bf00a3480c"),
"a" : 4,
"b" : 4,
"arr" : [
{
"a" : 6,
"b" : 6
},
{
"a" : 7,
"b" : 7
}
]
}
This will give me the number of element inside of the array:
db.getCollection('testCol').aggregate([{$match:{$and:[{a:{"$eq": 4}}]}},
{ $unwind : "$arr" },
{ $group: {
_id: '',
count: { $sum: 1 }}}
])
This was useful for me when I had to do count validation after loading data from Oracle (or any rdbms) into MongoDB when I am using a custom defined _id which isn't unique. We can push any entries with duplicated custom _id into array.
Comments
Post a Comment