社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  MongoDB

在MongoDB对象点表示法中使用变量

DragonBorn • 5 年前 • 286 次点击  

我想增加一个对象的属性值,如果它确实存在于数组中。

Mongo唱片:

{
    "_id" : ObjectId("5b7bdd9f0465e8345ba83aad"),
    "userID" : "400",
    "userName" : "Jon Snow",
    "pageName" : "1",
    "courseName" : "Maths",
    "socketID" : [
        "aswKWYyE1euk2GNIAAAD"
    ],
    "online" : true,
    "userHistory" : {
        "pagesVisited" : [
            {
                "page" : "1",
                "timesVisited" : 1
            }
        ],
        "coursesVisited" : [
            "Maths"
        ]
    },
    "date" : ISODate("2018-08-21T09:38:39.281Z")
}

在这里 userHistory.pagesVisited page 属性如果我得到值 再次,我想增加 timesVisited 类似财产:

"pagesVisited" : [
    {
       "page" : "1",
       "timesVisited" : 2
    }
],

以下是我没有运气的尝试:

let userDetails = {
   userID: queryUser.userID,
   userName: queryUser.username,
   pageName: queryUser.pageName,
   courseName: queryUser.courseName,
   socketID: [socket.id],
   online: true,
   userHistory: {
     pagesVisited: [
        {
          "page" : queryUser.pageName,
          "timesVisited" : 1
        }
     ],
     coursesVisited: [queryUser.courseName]
   },
   date: new Date()
};

onlineUsersDB.findOne({'userID': userDetails.userID}).then(async (user) => {
     if (user) {
         let page = {"page": queryUser.pageName, "timesVisited": 1};
         let course = queryUser.courseName;
         let updatedUser = await onlineUsersDB.findOneAndUpdate(
           {'userID': user.userID}, 
           {
             $set: {'online': true}, 
             $push: { 'socketID': socket.id },
           },
           { $addToSet: { 'userHistory.coursesVisited': course } },
           { returnOriginal: false }
         );
         let updatedUserPageRef = updatedUser.value.userHistory.pagesVisited;
         if (updatedUserPageRef) {
           let pageFound = await updatedUserPageRef.findIndex(item => item.page === page);
           if (pageFound >= 0) {
            let updatedUserPage = await onlineUsersDB.findOneAndUpdate(
              {'userID': updatedUser.value.userID},
             // Here I want to reference the variable pageFound
              {$inc: { 'userHistory.pagesVisited.[pageFound].timesVisited': 1 }},
              { returnOriginal: false }
            );
            console.log(JSON.stringify(updatedUserPage,null, 2));
           }
         }
         let users = await onlineUsersDB.find({'online': true}).toArray();
         io.to(room).emit('online-users', users);
         io.to(room).emit('user-back-online', updatedUser);
     } else {
         if (userDetails.userID !== '100') {
            await onlineUsersDB.insert(userDetails);
         }
         let users = await onlineUsersDB.find({'online': true}).toArray();
         io.to(room).emit('online-users', users);
     }
}).catch((e) => console.log(e));

在上面我的注释所在的代码中,我想引用变量 pageFound 在我的对象点符号中,就像这样:

{$inc: { 'userHistory.pagesVisited.[pageFound].timesVisited': 1 }}

当我给它一个硬编码的值,比如:

{$inc: { 'userHistory.pagesVisited.0.timesVisited': 1 }}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/37869
 
286 次点击  
文章 [ 1 ]  |  最新文章 5 年前
DragonBorn
Reply   •   1 楼
DragonBorn    6 年前

在做了一点实验之后,我让它像这样工作:

我使用模板文本将查询字符串分解为另一个变量。

let pageInc = `userHistory.pagesVisited.${pageFound}.timesVisited`;

然后像这样引用我查询中的变量:

{$inc: { [pageInc]: 1 }}

现在它开始工作了。