如何确定JSON字段的数据类型?MongoDB中能否查询该类型?
Great questions! Let's break this down step by step.
1. Determining a Field's Data Type in JSON
JSON has a small set of native data types, so you can spot a field's type just by looking at its value format:
- String: Enclosed in double quotes (like
"Fri Aug 04 05:42:03 +0000 2017"from your example) - Number: Numeric values without quotes (e.g.,
893346273255866400for youridfield) - Boolean:
trueorfalse(no quotes) - Array: Wrapped in square brackets
[] - Object: Wrapped in curly braces
{} - Null: Explicit
nullvalue
For your sample document, the created_at value is wrapped in double quotes, so it’s definitely a string type.
2. Checking Field Data Types in MongoDB
Absolutely, you can verify the data type of a specific field in MongoDB documents—here are two simple, reliable methods:
Method 1: Use the $type Query Operator
MongoDB’s $type operator lets you query documents where a field matches a specific data type. You can use either the type name (e.g., "string") or its corresponding numeric code (e.g., 2 for strings).
To confirm your created_at field is a string:
// Query using the type name db.your_collection.find({ "created_at": { $type: "string" } }) // Or use the numeric type code db.your_collection.find({ "created_at": { $type: 2 } })
If your sample document is returned, that confirms created_at is stored as a string.
Method 2: Inspect Individual Document Field Types
Grab a single document and use JavaScript’s typeof operator to check the field’s type directly in the MongoDB shell:
// Fetch the document (adjust the query to match your data) const doc = db.your_collection.findOne({ id: 893346273255866400 }) // Check the type of the created_at field typeof doc.created_at // Will return "string"
Bonus: Working with String Dates in Queries
Since your created_at is a string-formatted date, if you want to run date-based queries (like filtering by date range), you can convert it to a MongoDB Date type on the fly using $toDate:
// Find documents where created_at is on or after August 1, 2017 db.your_collection.find({ $expr: { $gte: [ { $toDate: "$created_at" }, ISODate("2017-08-01T00:00:00Z") ] } })
内容的提问来源于stack exchange,提问作者codex

