Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(db-mongodb): improve performance of all operations, up to 50% faster #9594

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
41 changes: 19 additions & 22 deletions packages/db-mongodb/src/count.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,47 @@
import type { CountOptions } from 'mongodb'
import type { Count, PayloadRequest } from 'payload'

import { flattenWhereToOperators } from 'payload'

import type { MongooseAdapter } from './index.js'

import { withSession } from './withSession.js'
import { getSession } from './getSession.js'
import { getHasNearConstraint } from './utilities/getHasNearConstraint.js'

export const count: Count = async function count(
this: MongooseAdapter,
{ collection, locale, req = {} as PayloadRequest, where },
) {
const Model = this.collections[collection]
const options: CountOptions = await withSession(this, req)

let hasNearConstraint = false
const session = await getSession(this, req)

if (where) {
const constraints = flattenWhereToOperators(where)
hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))
}
const hasNearConstraint = getHasNearConstraint(where)

const query = await Model.buildQuery({
locale,
payload: this.payload,
session,
where,
})

// useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.
const useEstimatedCount = hasNearConstraint || !query || Object.keys(query).length === 0

if (!useEstimatedCount && Object.keys(query).length === 0 && this.disableIndexHints !== true) {
// Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding
// a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,
// which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses
// the correct indexed field
options.hint = {
_id: 1,
}
}

let result: number
if (useEstimatedCount) {
result = await Model.estimatedDocumentCount({ session: options.session })
result = await Model.collection.estimatedDocumentCount()
} else {
result = await Model.countDocuments(query, options)
const options: CountOptions = { session }

if (this.disableIndexHints !== true) {
// Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding
// a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,
// which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses
// the correct indexed field
options.hint = {
_id: 1,
}
}

result = await Model.collection.countDocuments(query, options)
}

return {
Expand Down
41 changes: 19 additions & 22 deletions packages/db-mongodb/src/countGlobalVersions.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,47 @@
import type { CountOptions } from 'mongodb'
import type { CountGlobalVersions, PayloadRequest } from 'payload'

import { flattenWhereToOperators } from 'payload'

import type { MongooseAdapter } from './index.js'

import { withSession } from './withSession.js'
import { getSession } from './getSession.js'
import { getHasNearConstraint } from './utilities/getHasNearConstraint.js'

export const countGlobalVersions: CountGlobalVersions = async function countGlobalVersions(
this: MongooseAdapter,
{ global, locale, req = {} as PayloadRequest, where },
) {
const Model = this.versions[global]
const options: CountOptions = await withSession(this, req)

let hasNearConstraint = false
const session = await getSession(this, req)

if (where) {
const constraints = flattenWhereToOperators(where)
hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))
}
const hasNearConstraint = getHasNearConstraint(where)

const query = await Model.buildQuery({
locale,
payload: this.payload,
session,
where,
})

// useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.
const useEstimatedCount = hasNearConstraint || !query || Object.keys(query).length === 0

if (!useEstimatedCount && Object.keys(query).length === 0 && this.disableIndexHints !== true) {
// Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding
// a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,
// which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses
// the correct indexed field
options.hint = {
_id: 1,
}
}

let result: number
if (useEstimatedCount) {
result = await Model.estimatedDocumentCount({ session: options.session })
result = await Model.collection.estimatedDocumentCount()
} else {
result = await Model.countDocuments(query, options)
const options: CountOptions = { session }

if (Object.keys(query).length === 0 && this.disableIndexHints !== true) {
// Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding
// a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,
// which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses
// the correct indexed field
options.hint = {
_id: 1,
}
}

result = await Model.collection.countDocuments(query, options)
}

return {
Expand Down
41 changes: 19 additions & 22 deletions packages/db-mongodb/src/countVersions.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,47 @@
import type { CountOptions } from 'mongodb'
import type { CountVersions, PayloadRequest } from 'payload'

import { flattenWhereToOperators } from 'payload'

import type { MongooseAdapter } from './index.js'

import { withSession } from './withSession.js'
import { getSession } from './getSession.js'
import { getHasNearConstraint } from './utilities/getHasNearConstraint.js'

export const countVersions: CountVersions = async function countVersions(
this: MongooseAdapter,
{ collection, locale, req = {} as PayloadRequest, where },
) {
const Model = this.versions[collection]
const options: CountOptions = await withSession(this, req)

let hasNearConstraint = false
const session = await getSession(this, req)

if (where) {
const constraints = flattenWhereToOperators(where)
hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))
}
const hasNearConstraint = getHasNearConstraint(where)

const query = await Model.buildQuery({
locale,
payload: this.payload,
session,
where,
})

// useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.
const useEstimatedCount = hasNearConstraint || !query || Object.keys(query).length === 0

if (!useEstimatedCount && Object.keys(query).length === 0 && this.disableIndexHints !== true) {
// Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding
// a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,
// which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses
// the correct indexed field
options.hint = {
_id: 1,
}
}

let result: number
if (useEstimatedCount) {
result = await Model.estimatedDocumentCount({ session: options.session })
result = await Model.collection.estimatedDocumentCount()
} else {
result = await Model.countDocuments(query, options)
const options: CountOptions = { session }

if (this.disableIndexHints !== true) {
// Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding
// a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,
// which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses
// the correct indexed field
options.hint = {
_id: 1,
}
}

result = await Model.collection.countDocuments(query, options)
}

return {
Expand Down
48 changes: 24 additions & 24 deletions packages/db-mongodb/src/create.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,44 @@
import type { Create, Document, PayloadRequest } from 'payload'
import type { Create, PayloadRequest } from 'payload'

import type { MongooseAdapter } from './index.js'

import { getSession } from './getSession.js'
import { handleError } from './utilities/handleError.js'
import { sanitizeRelationshipIDs } from './utilities/sanitizeRelationshipIDs.js'
import { withSession } from './withSession.js'
import { transform } from './utilities/transform.js'

export const create: Create = async function create(
this: MongooseAdapter,
{ collection, data, req = {} as PayloadRequest },
) {
const Model = this.collections[collection]
const options = await withSession(this, req)
let doc
const session = await getSession(this, req)

const sanitizedData = sanitizeRelationshipIDs({
config: this.payload.config,
data,
fields: this.payload.collections[collection].config.fields,
})
const fields = this.payload.collections[collection].config.flattenedFields

if (this.payload.collections[collection].customIDType) {
sanitizedData._id = sanitizedData.id
data._id = data.id
}

transform({
adapter: this,
data,
fields,
operation: 'create',
})

try {
;[doc] = await Model.create([sanitizedData], options)
} catch (error) {
handleError({ collection, error, req })
}
const { insertedId } = await Model.collection.insertOne(data, { session })
data._id = insertedId

// doc.toJSON does not do stuff like converting ObjectIds to string, or date strings to date objects. That's why we use JSON.parse/stringify here
const result: Document = JSON.parse(JSON.stringify(doc))
const verificationToken = doc._verificationToken
transform({
adapter: this,
data,
fields,
operation: 'read',
})

// custom id type reset
result.id = result._id
if (verificationToken) {
result._verificationToken = verificationToken
return data
} catch (error) {
handleError({ collection, error, req })
}

return result
}
40 changes: 22 additions & 18 deletions packages/db-mongodb/src/createGlobal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,38 @@ import type { CreateGlobal, PayloadRequest } from 'payload'

import type { MongooseAdapter } from './index.js'

import { sanitizeInternalFields } from './utilities/sanitizeInternalFields.js'
import { sanitizeRelationshipIDs } from './utilities/sanitizeRelationshipIDs.js'
import { withSession } from './withSession.js'
import { getSession } from './getSession.js'
import { transform } from './utilities/transform.js'

export const createGlobal: CreateGlobal = async function createGlobal(
this: MongooseAdapter,
{ slug, data, req = {} as PayloadRequest },
) {
const Model = this.globals

const global = sanitizeRelationshipIDs({
config: this.payload.config,
data: {
globalType: slug,
...data,
},
fields: this.payload.config.globals.find((globalConfig) => globalConfig.slug === slug).fields,
})
const fields = this.payload.config.globals.find(
(globalConfig) => globalConfig.slug === slug,
).flattenedFields

const options = await withSession(this, req)
transform({
adapter: this,
data,
fields,
globalSlug: slug,
operation: 'create',
})

let [result] = (await Model.create([global], options)) as any
const session = await getSession(this, req)

result = JSON.parse(JSON.stringify(result))
const { insertedId } = await Model.collection.insertOne(data, { session })
;(data as any)._id = insertedId

// custom id type reset
result.id = result._id
result = sanitizeInternalFields(result)
transform({
adapter: this,
data,
fields,
operation: 'read',
})

return result
return data
}
Loading
Loading