如何使用MongoDB在字段中搜索字符串或数字?
您可以为此使用$in运算符。首先让我们创建一个包含文档的集合-
> db.searchForStringOrNumberDemo.insertOne( { "_id": new ObjectId(), "StudentName": "Larry", "StudentDetails": { "StudentMarks": { "StudentMongoDBMarks": [44] } } } ); { "acknowledged" : true, "insertedId" : ObjectId("5ce2407c36e8b255a5eee944") } > db.searchForStringOrNumberDemo.insertOne( { "_id": new ObjectId(), "StudentName": "Larry", "StudentDetails": { "StudentMarks": { "StudentMongoDBMarks": ["44"] } } } ); { "acknowledged" : true, "insertedId" : ObjectId("5ce240f036e8b255a5eee945") }
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.searchForStringOrNumberDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5ce2407c36e8b255a5eee944"), "StudentName" : "Larry", "StudentDetails" : { "StudentMarks" : { "StudentMongoDBMarks" : [ 44 ] } } } { "_id" : ObjectId("5ce240f036e8b255a5eee945"), "StudentName" : "Larry", "StudentDetails" : { "StudentMarks" : { "StudentMongoDBMarks" : [ "44" ] } } }
以下是在字段中搜索字符串或数字的查询-
>db.searchForStringOrNumberDemo.find({"StudentDetails.StudentMarks.StudentMongoDBMarks": { "$in": ["44",44] } });
这将产生以下输出-
{ "_id" : ObjectId("5ce2407c36e8b255a5eee944"), "StudentName" : "Larry", "StudentDetails" : { "StudentMarks" : { "StudentMongoDBMarks" : [ 44 ] } } } { "_id" : ObjectId("5ce240f036e8b255a5eee945"), "StudentName" : "Larry", "StudentDetails" : { "StudentMarks" : { "StudentMongoDBMarks" : [ "44" ] } } }