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

Merged
merged 15 commits into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 18 additions & 23 deletions packages/db-mongodb/src/count.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,47 @@
import type { CountOptions } from 'mongodb'
import type { Count } from 'payload'

import { flattenWhereToOperators } from 'payload'

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

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

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

let hasNearConstraint = false

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: 18 additions & 23 deletions packages/db-mongodb/src/countGlobalVersions.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,47 @@
import type { CountOptions } from 'mongodb'
import type { CountGlobalVersions } from 'payload'

import { flattenWhereToOperators } from 'payload'

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

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

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

let hasNearConstraint = false

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: 18 additions & 23 deletions packages/db-mongodb/src/countVersions.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,47 @@
import type { CountOptions } from 'mongodb'
import type { CountVersions } from 'payload'

import { flattenWhereToOperators } from 'payload'

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

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

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

let hasNearConstraint = false

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
50 changes: 23 additions & 27 deletions packages/db-mongodb/src/create.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,44 @@
import type { CreateOptions } from 'mongoose'
import type { Create, Document } from 'payload'
import type { Create } from 'payload'

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

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

export const create: Create = async function create(
this: MongooseAdapter,
{ collection, data, req },
) {
const Model = this.collections[collection]
const options: CreateOptions = {
session: await getSession(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
}
41 changes: 21 additions & 20 deletions packages/db-mongodb/src/createGlobal.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,39 @@
import type { CreateOptions } from 'mongoose'
import type { CreateGlobal } from 'payload'

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

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

export const createGlobal: CreateGlobal = async function createGlobal(
this: MongooseAdapter,
{ slug, data, req },
) {
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: CreateOptions = {
session: await getSession(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