我在 MongoDB 中有一个文档,我想获取该文档的 ObjectId,但到目前为止我还没有找到对我执行此操作的方法。
查询示例:
user= db.users.find({userName:"Andressa"})
这会返回这个:
{ "_id" : ObjectId("53b1c579bdf3de74f76bdac9"), "userid" : 0, "userName" : "Andressa", "userEmail" : "[email protected]", "teams" : [ 1, 2, 3 ] }
我想获取ObjectId来进行另一个查询。
示例:
userID = `user._id();` //but this does not work, of course, its an example
因此,我可以使用 ObjectId 执行另一个查询,如下所示:
userFind = db.users.find({_id: userID})
更新: 这段代码:
db.teams.find({_id:{$in: user.teams}})
返回此错误:
error: {
"$err" : "Can't canonicalize query: BadValue $in needs an array",
"code" : 17287
有人知道吗?
在 mongo shell 中,您可以使用它来检索
_id
:
user._id.str
或
user._id.toString()
请参阅文档:http://docs.mongodb.org/manual/reference/method/ObjectId.valueOf/
我明白了!实际上,我可以通过这段代码来做到这一点:
而不是仅仅输入:
user = db.users.findOne({userName:"And"})
我刚刚做了:
var user = db.users.findOne({userName:"And"})
和
user._id
返回ObjectId(“someId”) ,如果我想将其保留在某个变量中,我会这样做:
var Id = user._id.
关于第二个问题,我不知道。
我遇到了我认为是相同的问题 - 如何从未知的 mongo 文档中检索 ObjectId。我已经构建了一个通用数据上下文,并且在更新和删除方法中需要 _id 。在寻找有关如何执行此操作的答案时发现您的问题后,我决定发布最终对我有用的内容。
private BsonValue GetId<TEntity>(TEntity entity)
{
var bsonDoc = entity.ToBsonDocument();
return bsonDoc.GetElement("_id").Value;
}
然后我像这样使用它:
var id = GetId<TEntity>(entity);
var filter = builder.Eq("_id", id);
var doc = collection.Find(filter).SingleOrDefault();
希望这有帮助。
我认为你正在寻找的是获取id的值:
user= db.users.find({userName:"Andressa"})
.then(data=>return data._id.valueOf())
.catch(err=>console.log(err));
使用 MongoDB Node.js 驱动和 ES6 解构
const { _id } = db.collection("users").findOne({ userName:"Andressa" })
或者更好的是,在重组时重命名......
const { _id: userId } = db.collection("users").findOne({ userName:"Andressa" })
然后可以根据需要在代码中使用 userId...
您可以使用 find() 方法来实现这一点。
db.collection.find() 方法不返回实际文档,但将光标返回到文档。通过迭代光标,您将看到该文档中的字段。
代码:
var cursor=db.collection.find()
var objectId= cursor.next()._id
上面的语句从当前游标实例中获取ObjectId的值。 如果您要检索所有 objectId,那么通过遍历游标您将获得 ObjectId 的所有值。
要直接使用第一步中收到的 objectId 查找文档,您可以使用以下代码片段:
db.collection.find( { "_id": objectId},{ fields Of Your Choice } )
试试这个(对于 Node v12.16.3 / MongoDB MongoDB v4.2.6)
// find if a value exists
collection.find({ "criteria1": value1, "criteria2": value2 }).toArray
(function(err, doc) {
if (err) {
console.log('Error, Please Try Again');
}
else if (doc.length === 0) {
console.log('Does Not Exist');
} else {
console.log(doc);
console.log(doc[0]._id)
}
});
在这里我发现我的 HTTP 响应中的 Mongo _Id 为 JSON
产品实体:
@Document(collection= "Products")
@Data
public class ProductsEntity {
@Field("_id")
private ObjectId _id;
private int index;
private String productId;
private String productName;
private String productDescription;
}
我的产品型号:
public class Products {
@Field("_id")
private ObjectId _id;
private int index;
private String productID;
private String productName;
private String productDescription;
}
这里是我的存储库方法与 Query 、 Criteria 和 MongoOperations 一起使用。
@Autowired
private MongoOperations operations;
public ProfileEntity findByProductID(String productID){
Query query = new Query();
query = Query.query(Criteria.where("productID").is(productID));
List<ProductEntity> entity = operations.find(query, ProductEntity.class);
System.out.println(" Profile data from profile collection -- "+ entity);
return entity.get(0);
}
API 的响应:
{
"productslist": [
{
"_id": {
"timestamp": 1665062474,
"date": "2022-10-06T13:21:14.000+00:00"
},
"index": 4,
"productID": "4",
"productName": "Fourth dashboard",
"productDescription": "This is Fourth dashboard."
},
{
"_id": {
"timestamp": 1665377430,
"date": "2022-10-10T04:50:30.000+00:00"
},
"index": 5,
"productID": "5",
"productName": "Fifth dashboard",
"productDescription": "This is Fifth dashboard."
}
]
}
val id = entity.id.toHexString()
val objectId = ObjectId(id)