I have a collection product which looks like this.
{
should_show: {
type: String,
enum: ['always', 'never', 'on_date'],
default: 'always',
},
show_start_date: { type: Date },
show_end_date: { type: Date },
categories: [{ type: ObjectId }],
price: number,
}
find condition like this works fine when I find many products.
const condition = {
'$and': [
{ '$and': [ { categories: '61bdd930fb1dfb1f65a21f13' } ] },
{
'$or': [
{ should_show: 'always' },
{
should_show: 'on_date',
show_start_date: { '$lt': 2022-01-03T08:56:19.589Z },
show_end_date: { '$gt': 2022-01-03T08:56:19.589Z }
}
]
}
]
}
Products.find(condition)
But I changed my business logic to use Model.aggregate() instead of `Model.find()
(because I have to use allowdiskuse option)
const condition = {
'$and': [
{ '$and': [ { categories: '61bdd930fb1dfb1f65a21f13' } ] },
{
'$or': [
{ should_show: 'always' },
{
should_show: 'on_date',
show_start_date: { '$lt': 2022-01-03T08:56:19.589Z },
show_end_date: { '$gt': 2022-01-03T08:56:19.589Z }
}
]
}
]
}
Products.aggregate([
{ $match: condition },
])
And returned results is always empty array []
I changed my condition simpler like this
const condition = {
'$and': [ { categories: '61bdd930fb1dfb1f65a21f13' } ],
'$or': [
{ should_show: 'always' },
{
should_show: 'on_date',
show_start_date: { '$lt': 2022-01-03T08:56:50.161Z },
show_end_date: { '$gt': 2022-01-03T08:56:50.161Z }
}
]
}
Products.aggregate([
{ $match: condition },
])
but still returns empty array.
How should I fix this problem?
Self Answer:
I have to pass ObjectId by explicit ObjectId type, not string.
const condition = {
'$and': [
{ '$and': [{
// like this:
categories: Mongoose.Types.ObjectId('61bdd930fb1dfb1f65a21f13'),
}] },
{
'$or': [
{ should_show: 'always' },
{
should_show: 'on_date',
show_start_date: { '$lt': 2022-01-03T08:56:19.589Z },
show_end_date: { '$gt': 2022-01-03T08:56:19.589Z }
}
]
}
]
}
Products.aggregate([
{ $match: condition },
])
Related
I am having a similar collection
db={
collectionA: [
{
"id": ObjectId("63b7c24c06ebe7a8fd11777b"),
"uniqueRefId": "UUID-2023-0001",
"products": [
{
"productIndex": 1,
"isProdApproved": false,
"productCategory": ObjectId("63b7c24c06ebe7a8fd11777b"),
"productOwners": [
{
_id: ObjectId("63b7c2fd06ebe7a8fd117781"),
iApproved: false
},
{
_id: ObjectId("63b7c2fd06ebe7a8fd117782"),
iApproved: false
}
]
},
{
"productIndex": 2,
"isProdApproved": false,
"productCategory": ObjectId("63b7c24c06ebe7a8fd11777b"),
"productOwners": [
{
_id: ObjectId("63b7c2fd06ebe7a8fd117781"),
iApproved: false
},
{
_id: ObjectId("63b7c2fd06ebe7a8fd117783"),
iApproved: false
}
]
},
{
"productIndex": 3,
"productCategory": "",
"productOwners": ""
}
]
}
]
}
I want to find the productOwner whose _id is 63b7c2fd06ebe7a8fd117781 in the productOwners and update the isApproved and isprodApproved to true. Other data will remain as it is.
I have tried this but it is only updating the first occurance
db.collectionA.update(
{
_id: ObjectId('63b7c24c06ebe7a8fd11777b'),
'products.productOwners._id': ObjectId('63b7c2fd06ebe7a8fd117781'),
},
{ $set: { 'products.$.productOwners.$[x].isApproved': true } },
{ arrayFilters: [{ 'x._id': ObjectId('63b7c2fd06ebe7a8fd117781') }] }
);
This one should work:
db.collection.updateMany({},
[
{
$set: {
products: {
$map: {
input: "$products",
as: "product",
in: {
$cond: {
if: { $eq: [{ $type: "$$product.productOwners" }, "array"] },
then: {
$mergeObjects: [
"$$product",
{ isProdApproved: { $in: [ObjectId("63b7c2fd06ebe7a8fd117781"), "$$product.productOwners._id"] } },
{
productOwners: {
$map: {
input: "$$product.productOwners",
as: 'owner',
in: {
$mergeObjects: [
"$$owner",
{ iApproved: { $eq: ["$$owner._id", ObjectId("63b7c2fd06ebe7a8fd117781")] } }
]
}
}
}
}
]
},
else: "$$product"
}
}
}
}
}
}
]
)
However, the data seem to be redundant. Better update only products.productOwners.iApproved and then derive products.isProdApproved from nested elements:
db.collection.aggregate([
{
$set: {
products: {
$map: {
input: "$products",
as: "product",
in: {
$cond: {
if: { $eq: [{ $type: "$$product.productOwners" }, "array"] },
then: {
$mergeObjects: [
"$$product",
{ isProdApproved: { $anyElementTrue: ["$$product.productOwners.iApproved"] } },
]
},
else: "$$product"
}
}
}
}
}
}
])
These are my documents:
[
{
uuid: 1,
emailNotifications: [
{
targetEmailAddress: "w#w.pl"
},
{
targetEmailAddress: "w2#w.pl"
}
]
},
{
uuid: 2,
emailNotifications: [
{
targetEmailAddress: "xxxw#w.pl"
},
{
targetEmailAddress: "xxxw2#w.pl"
},
]
},
]
I want query those with emailNotifications.targetEmailAddress equals to "w#w.pl":
db.collection.find({
emailNotifications: {
$elemMatch: {
targetEmailAddress: "w#wp.pl"
}
}
})
but it finds nothing. Where is the error?
Your value of targetEmailAdress in the query is wrong. You don't have w#wp.pl in your documents.
I am trying to match nested fields in a document in mongo but my query is not working.
Configuration:
[
{
linenumber: "car",
type: "004",
nested: {
info: {
subinfo: "B"
}
},
},
{
linenumber: "car",
type: "005",
nested: {
info: {
subinfo: "G"
}
},
}
]
query:
db.collection.aggregate([
{
$match: {
$and: [
{
linenumber: "car"
},
{
nested: {
info: {
subinfo: {
$in: [
"B",
"G"
]
}
}
}
}
]
}
},
{
$group: {
_id: null,
types: {
$addToSet: "$type"
}
}
}
])
I am using the mongoplayground to test. Here is the link:
https://mongoplayground.net/p/nND59iO1339
I am getting no documents found.
You are almost there. You need to use dot notation.
play
db.collection.aggregate([
{
$match: {
$and: [
{
linenumber: "car"
},
{
"nested.info.subinfo": { //Dot notation
$in: [
"B",
"G"
]
}
}
]
}
},
{
$group: {
_id: null,
types: {
$addToSet: "$type"
}
}
}
])
I am having issues with referencing a nested array item in a $cond statement.
db.getCollection('bookings').aggregate([
{
$lookup: {
from: "listings",
localField: "listingId",
foreignField: "_id",
as: "listing"
}
},
{
$match: {
$and: [
{
locationId: ObjectId("5c0f0c882fcf07fb08890c27")
},
{
$or: [
{
$and: [
{
state: "booked"
},
{
startDate: {
$lte: new Date()
}
},
{
startDate: {
$gte: ISODate("2019-12-18T07:00:00.000Z")
}
}
]
},
{
$and: [
{
listing: {
$elemMatch: {
inspectionStatus: "none"
}
}
},
{
endDate: {
$lte: new Date()
}
},
{
endDate: {
$gte: ISODate("2019-12-18T07:00:00.000Z")
}
},
{
state: {
$in: [
"active",
"returned"
]
}
}
]
},
{
$and: [
{
state: {
$ne: "cancelled"
}
},
{
$or: [
{
$and: [
{
startDate: {
$gte: ISODate("2019-12-20T07:00:00.993Z")
}
},
{
startDate: {
$lte: ISODate("2019-12-21T06:59:59.999Z")
}
}
]
},
{
$and: [
{
endDate: {
$gte: ISODate("2019-12-20T07:00:00.993Z")
}
},
{
endDate: {
$lte: ISODate("2019-12-21T06:59:59.999Z")
}
}
]
}
]
}
]
}
]
}
]
}
},
{
$addFields: {
isLate: {
$cond: [
{
$or: [
{
$and: [
{
$eq: [
"$listing.0.inspectionStatus",
"none"
]
},
{
$lte: [
"$endDate",
new Date()
]
},
{
$gte: [
"$endDate",
ISODate("2019-12-18T07:00:00.000Z")
]
},
{
$in: [
"$state",
[
"active",
"returned"
]
]
},
]
},
{
$and: [
{
$eq: [
"$state",
"booked"
]
},
{
$lte: [
"$startDate",
new Date()
]
},
{
$gte: [
"$startDate",
ISODate("2019-12-18T07:00:00.000Z")
]
}
]
}
]
},
true,
false
]
}
}
}
])
In the above, the following lines in the $cond statement does not work at all:
$eq: [
"$listing.0.inspectionStatus",
"none"
]
My question is - how do I make the above work? Note that there is always only one array item in the listing field after the lookup (never more than one array item in there). I've tried different variations like $listing.$0.$inspectionStatus - but nothing seems to work. I could go down the trajectory of researching group and filter - but I feel like this is overkill when I simply always want to access the first and only item in the listing array.
Please use $in keyword instead of $eq keyword in $cond keyword
db.demo1.aggregate([
{
$lookup: {
from: "demo2",
localField: "listingId",
foreignField: "_id",
as: "listing"
}
},
{
$match: {
$and: [
{
locationId: ObjectId("5c0f0c882fcf07fb08890c27")
},
{
$or: [
{
$and: [
{
state: "booked"
},
{
startDate: {
$lte: new Date()
}
},
{
startDate: {
$gte: ISODate("2019-12-18T07:00:00.000Z")
}
}
]
},
{
$and: [
{
listing: {
$elemMatch: {
inspectionStatus: "none"
}
}
},
{
endDate: {
$lte: new Date()
}
},
{
endDate: {
$gte: ISODate("2019-12-18T07:00:00.000Z")
}
},
{
state: {
$in: [
"active",
"returned"
]
}
}
]
},
{
$and: [
{
state: {
$ne: "cancelled"
}
},
{
$or: [
{
$and: [
{
startDate: {
$gte: ISODate("2019-12-20T07:00:00.993Z")
}
},
{
startDate: {
$lte: ISODate("2019-12-21T06:59:59.999Z")
}
}
]
},
{
$and: [
{
endDate: {
$gte: ISODate("2019-12-20T07:00:00.993Z")
}
},
{
endDate: {
$lte: ISODate("2019-12-21T06:59:59.999Z")
}
}
]
}
]
}
]
}
]
}
]
}
},
{
$addFields: {
isLate: {
$cond: [
{
$or: [
{
$and: [
{
$in: [
"none",
"$listing.inspectionStatus",
]
},
{
$lte: [
"$endDate",
new Date()
]
},
{
$gte: [
"$endDate",
ISODate("2019-12-18T07:00:00.000Z")
]
},
{
$in: [
"$state",
[
"active",
"returned"
]
]
},
]
},
{
$and: [
{
$eq: [
"$state",
"booked"
]
},
{
$lte: [
"$startDate",
new Date()
]
},
{
$gte: [
"$startDate",
ISODate("2019-12-18T07:00:00.000Z")
]
}
]
}
]
},
true,
false
]
}
}
}
])
Provided I have following collections
Customers
[
{
uuid: "first",
culture: "it-it"
},
{
uuid: "second",
culture: "de-de"
}
]
Vehicles
[
{
model: "mymodel",
users: [
{
uuid: "first",
isOwner: true,
createdOn: "2019-05-15T06: 00: 00"
}
]
},
{
model: "mymodel",
users: [
{
uuid: "first",
isOwner: false,
createdOn: "2019-05-15T06: 00: 00"
},
{
uuid: "second",
isOwner: true,
createdOn: "2019-05-15T06: 00: 00"
}
]
}
]
And following query:
db.customers.aggregate([
{
$lookup: {
from: "vehicles",
let: {
uuid: "$uuid"
},
pipeline: [
{
$match: {
$expr: {
$in: [
"$$uuid",
"$users.uuid"
]
}
}
},
{
$project: {
model: 1,
users: {
$filter: {
input: "$users",
as: "user",
cond: {
$eq: [
"$$user.uuid",
"$$uuid"
]
}
}
}
}
},
{
$unwind: "$users"
},
{
$replaceRoot: {
newRoot: {
isOwner: "$users.isOwner",
createdOn: "$users.createdOn"
}
}
}
],
as: "vehicles"
}
},
{
$facet: {
"createdOn": [
{
$match: {
"vehicles": {
$elemMatch: {
isOwner: true,
$and: [
{
"createdOn": {
$gte: "2019-05-15T00: 00: 00"
}
},
{
"createdOn": {
$lt: "2019-05-16T00: 00: 00"
}
}
]
}
}
}
},
{
$project: {
culture: 1,
count: {
$size: "$vehicles"
}
}
},
{
$group: {
_id: 0,
"total": {
$sum: "$count"
}
}
}
]
}
},
{
$project: {
"CreatedOn": {
$arrayElemAt: [
"$CreatedOn.total",
0
]
}
}
}
])
I get following result:
[
{
"createdOn": 2
}
]
What I would like to achieve is a result as follows:
[
{
culture: "it-it",
results: {
"createdOn": 1
}
},
{
culture: "de-de",
results: {
"createdOn": 1
}
}
]
But I cannot seem to figure out where I can group so that I can get that result.
Can someone show me the way to do this?
The query is more complex with more metrics so this is a trimmed down version of what I have.
I tried grouping everywhere but fail to get the desired result I want.
The following query can get us the expected output:
db.customers.aggregate([
{
$lookup: {
"from": "vehicles",
"let": {
"uuid": "$uuid"
},
"pipeline": [
{
$unwind: "$users"
},
{
$match: {
$expr: {
$and: [
{
$eq: ["$users.uuid", "$$uuid"]
},
{
$eq: ["$users.isOwner", true]
},
{
$gte: ["$users.createdOn", "2019-05-15T00: 00: 00"]
},
{
$lte: ["$users.createdOn", "2019-05-16T00: 00: 00"]
}
]
}
}
},
{
$count:"totalVehicles"
}
],
as: "vehiclesInfo"
}
},
{
$unwind: {
"path": "$vehiclesInfo",
"preserveNullAndEmptyArrays": true
}
},
{
$group: {
"_id": "$culture",
"culture": {
$first: "$culture"
},
"createdOn": {
$sum: "$vehiclesInfo.totalVehicles"
}
}
},
{
$project: {
"_id": 0,
"culture": 1,
"results.createdOn": "$createdOn"
}
}
]).pretty()
Output:
{ "culture" : "de-de", "results" : { "createdOn" : 1 } }
{ "culture" : "it-it", "results" : { "createdOn" : 1 } }